Unity中foreach会增加GC
unity中for效率比foreach高?
在unity中使用foreach遍历集合会增加gc alloc,参考的话题:
foreach造成gc alloc
C#遍历集合方法
ToArray
ToArray等于把Dictionary拷贝了一份
使用Linq
Enumerable.ElementAt<TSource> (IEnumerable<TSource>, Int32)
参考:
方法代码
public static void Main(string[] args){ Dictionarydictionary =new Dictionary (); dictionary["engine1"] = "unity"; dictionary["engine2"] = "cocos"; //方法一 var array = dictionary.ToArray(); for (int idx = 0; idx < array.Count(); idx++) { var itemKey = array[idx].Key; var itemValue = array[idx].Value; Console.Write("key:{0} ,value:{1}\n", itemKey, itemValue); } //方法二 for (int index = 0; index < dictionary.Count; index++) { //根据索引获取 var item = dictionary.ElementAt(index); var itemKey = item.Key; var itemValue = item.Value; Console.Write("\nkey:{0} ,value:{1}\n", itemKey, itemValue); }}
GetEnumerator(Unity推荐使用)
static void Main(string[] args){ Dictionarydict = new Dictionary (); dict.Add("C#", "4.5"); dict.Add("Java", "8"); dict.Add("Python", "3"); Dictionary .Enumerator etor = dict.GetEnumerator(); while (etor.MoveNext()) { Console.WriteLine("key = {0}, value = {1}",etor.Current.Key, etor.Current.Value); }}