且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-08-13 22:43:10



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

 

方法代码

Unity减少GC Alloc之 使用for替换foreach
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);
    }

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

GetEnumerator(Unity推荐使用)

Unity减少GC Alloc之 使用for替换foreach
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);
    }
}
Unity减少GC Alloc之 使用for替换foreach

 

本文转自赵青青博客园博客,原文链接:http://www.cnblogs.com/zhaoqingqing/p/5059342.html,如需转载请自行联系原作者