You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Dictionay如果遍历,采用foreach (var v in dictionary.Values),同时注意dictionary.TryGetValue()消耗较大。
容器选择很重要,前期数据结构设计好,在移动端可以减少cpu运算量,避免cpu发热量过高导致掉帧。
尽量减少在Update中每帧都通过容器遍历数据。
测试代码
usingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingUnityEngine;usingUtils;namespaceTest{publicclassTestCollectionsTraversal:MonoBehaviour{privateTimeSpan_timeSpan;privateDateTime_lastDateTime;privatereadonlyStringBuilder_logTmp=newStringBuilder(1000);privatevoidStart(){varcount=1000000;LoggerHelper.LogNormal(DeviceInfo.Info());LoggerHelper.LogNormal($"CollectionsTraversal_TraversalCount_{count}\n");for(vari=0;i<5;i++){_logTmp.Clear();_logTmp.Append($"-----------------Test the {i+1} times \n");TestList(count);TestArray(count);TestDictionary(count);LoggerHelper.LogNormal(_logTmp.ToString());}count=10000000;LoggerHelper.LogNormal($"Array_TraversalCount_{count}\n");for(vari=0;i<5;i++){_logTmp.Clear();_logTmp.Append($"-----------------Test the {i+1} times \n");TestArray(count);LoggerHelper.LogNormal(_logTmp.ToString());}}privatevoidTestList(intcount){varl=newList<int>(count);for(vari=0;i<count;++i){l.Add(i);}_lastDateTime=DateTime.Now;varn=l.Count;for(vari=0;i<n;++i){varv=l[i];}_timeSpan=DateTime.Now.Subtract(_lastDateTime);_logTmp.Append($"List For Used Time {_timeSpan.TotalMilliseconds} milliseconds\n");_lastDateTime=DateTime.Now;foreach(varvinl){varv2=v;}_timeSpan=DateTime.Now.Subtract(_lastDateTime);_logTmp.Append($"List Foreach Used Time {_timeSpan.TotalMilliseconds} milliseconds\n");}privatevoidTestArray(intcount){vararray=newint[count];for(vari=0;i<count;++i){array[i]=i;}_lastDateTime=DateTime.Now;varn=array.Length;for(vari=0;i<n;++i){varv=array[i];}_timeSpan=DateTime.Now.Subtract(_lastDateTime);_logTmp.Append($"Array For Used Time {_timeSpan.TotalMilliseconds} milliseconds\n");_lastDateTime=DateTime.Now;foreach(varvinarray){varv2=v;}_timeSpan=DateTime.Now.Subtract(_lastDateTime);_logTmp.Append($"Array Foreach Used Time {_timeSpan.TotalMilliseconds} milliseconds\n");}privatevoidTestDictionary(intcount){vardic=newDictionary<int,string>(count);for(vari=0;i<count;++i){dic.Add(i,"test");}_lastDateTime=DateTime.Now;varn=dic.Count;for(vari=0;i<n;++i){dic.TryGetValue(i,outvarv);}_timeSpan=DateTime.Now.Subtract(_lastDateTime);_logTmp.Append($"Dictionary For Used Time {_timeSpan.TotalMilliseconds} milliseconds\n");_lastDateTime=DateTime.Now;foreach(varvindic.Values){varv2=v;}_timeSpan=DateTime.Now.Subtract(_lastDateTime);_logTmp.Append($"Dictionary Foreach Used Time {_timeSpan.TotalMilliseconds} milliseconds\n");}}}