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