Unity减少GC Alloc之 使用for替换foreach


Unity中foreach会增加GC

unity中for效率比foreach高?

在unity中使用foreach遍历集合会增加gc alloc,参考的话题:作为Unity3D的脚本而言,c#中for是否真的比foreach效率更高?

foreach造成gc alloc

Unity Mono的foreach造成GC Alloc的BUG与实测

 

C#遍历集合方法

ToArray

ToArray等于把Dictionary拷贝了一份

 

使用Linq

Enumerable.ElementAt<TSource>  (IEnumerable<TSource>, Int32)

参考:https://msdn.microsoft.com/zh-cn/library/bb299233%28v=vs.110%29.aspx

 

方法代码

public static void Main(string[] args)
{
    Dictionary<string,string> dictionary =new Dictionary<string, string>();
    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)
{
    Dictionary<string, string> dict = new Dictionary<string, string>();
    dict.Add("C#", "4.5");
    dict.Add("Java", "8");
    dict.Add("Python", "3");
    Dictionary<string, string>.Enumerator etor = dict.GetEnumerator();
    while (etor.MoveNext())
    {
        Console.WriteLine("key = {0}, value = {1}",etor.Current.Key, etor.Current.Value);
    }
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM