Unity减少GC Alloc之 使用for替换foreach
本文为作者原创,转载请注明出处:https://www.cnblogs.com/zhaoqingqing/p/5059342.html
Unity中foreach会增加GC#
unity中for效率比foreach高?#
在unity中使用foreach遍历集合会增加gc alloc,参考的话题:作为Unity3D的脚本而言,c#中for是否真的比foreach效率更高?
foreach造成gc alloc#
Unity Mono的foreach造成GC Alloc的BUG与实测
在Unity5.5.5p1中unity解决了此问题。但如果在ILRuntime中使用,依然建议使用for代替foreace
因为在于foreach生成中的IL代码中会有box.
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); } }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 10亿数据,如何做迁移?
· 推荐几款开源且免费的 .NET MAUI 组件库
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 易语言 —— 开山篇
· Trae初体验