少用foreach

来源:互联网 发布:微信跳转到淘宝app 编辑:程序博客网 时间:2024/04/29 11:54
  1. //抛开其他的不说,我只关注GC Alloc,因为这点是造成unity游戏偶尔卡帧的罪魁祸首,举一个代码例子:  
  2.   
  3. using UnityEngine;   
  4. using System.Collections;  
  5.   
  6. public class ForeachTest : MonoBehaviour {  
  7.   
  8.     protected ArrayList m_array;  
  9.   
  10.     void Start ()   
  11.     {   
  12.         m_array = new ArrayList();   
  13.         for (int i = 0; i < 2; i++)   
  14.             m_array.Add(i);   
  15.     }   
  16.       
  17.     void Update ()   
  18.     {   
  19.         for (int i = 0; i < 1000; i++)   
  20.         {   
  21.             foreach (int e in m_array)   
  22.             {   
  23.                 //big gc alloc!!! do not use this code!   
  24.             }   
  25.         }  
  26.   
  27.         for (int i = 0; i < 1000; i++)   
  28.         {   
  29.             for (int k = 0; k < m_array.Count; k++)   
  30.             {   
  31.                 //no gc alloc!!   
  32.             }   
  33.         }   
  34.     }   
  35. }  
  36.   
  37. 第一个循环大概会造成2.3K的GC Alloc(什么事都没做就耗费这么多GC。。。)。  
  38.   
  39. 第二个循环则没有任何GC Alloc。  
  40.   
  41. 所以,不要途方便,到处哪都用foreach循环。  
0 0