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);
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值