Unity 测试Transform cache和不cache的区别

关于Transform的cache问题:

大致看了下:

https://forum.unity.com/threads/cache-transform-really-needed.356875/

Transform cache的却会好一点点

 

有种Lazy的方式 可以在使用的时候lazy cache 去get  :

Lazy<Transform> _cameraTransform = new Lazy<Transform>(() => Camera.main.transform);

 

不过。。。。

在开发期 也许不需要太关注这件事情,而且cache后由于赋值顺序问题 也许还要处理一些logic的bug。  最后依Profiler为准, 并先处理大头的overhead。大概率在Profiler的前期是轮不到Transform 。。。

 

 

测试的结果:

result:

Not much difference 10000 times:
No caching:
TotalMilliseconds:1.6433
Caching:
TotalMilliseconds:0.5658

little different:
100000 times:
TotalMilliseconds:14.2513
TotalMilliseconds:5.1719

复制代码
 1 using System.Collections;
 2 using System.Collections.Generic;
 3 using System.Diagnostics;
 4 using UnityEngine;
 5 
 6 public class TestTransformWithCache : MonoBehaviour
 7 {
 8     private Transform myCameraCacheTransform;
 9     [SerializeField] private uint calls;
10  
11     private void Start() {
12         myCameraCacheTransform = Camera.main.transform;
13         print("No caching:");
14         Stopwatch watch = new Stopwatch();
15         watch.Start();
16         for (uint i = 0; i < calls; i++) TestNoCache();
17         watch.Stop();
18         print("TotalMilliseconds:"+ watch.Elapsed.TotalMilliseconds);
19         
20         print("Caching:");
21         Stopwatch watch2 = new Stopwatch();
22         watch2.Start();
23         for (uint i = 0; i < calls; i++) TestCache();
24         watch2.Stop();
25         print("TotalMilliseconds:"+ watch2.Elapsed.TotalMilliseconds);
26     }
27  
28     private void TestNoCache() {
29         Vector3 v = Vector3.zero;
30         v = Camera.main.transform.position;
31     }
32  
33     private void TestCache() {
34         Vector3 v = Vector3.zero;
35         v = myCameraCacheTransform.position;
36     }
37 }
复制代码

 

posted @   sun_dust_shadow  阅读(81)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示