关于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 }
标签:TotalMilliseconds,cache,watch,Transform,private,Unity,Stopwatch From: https://www.cnblogs.com/sun-shadow/p/17189030.html