[英]Which variable declaration optimize memory performance
哪種方法可以優化內存或相同? 方法1的 GameObject
是否為每個循環創建一個新的內存分配?,因為我相信方法2的 GameObject
使用相同的內存引用。
Method 1
是否會創建GC或創建會降低性能的新內存分配?
方法1
foreach (GameObject child in childs)
{
GameObject obj = otherObj.GetComponent<Transform>().gameObject;
//do something with obj
}
foreach(GameObject child in child2)
{
GameObject obj = otherObj2.GetComponent<Transform>().gameObject;
//do something with obj
}
方法2
GameObject obj;
foreach (GameObject child in childs)
{
obj = otherObj.GetComponent<Transform>().gameObject;
//do something with obj
}
foreach(GameObject child in child2)
{
obj = otherObj2.GetComponent<Transform>().gameObject;
//do something with obj
}
兩種方法的GC壓力相同。 罪魁禍首不是obj
,而是foreach
。 如果使用for
進行迭代,則可以在沒有任何內存分配的情況下執行以下循環:
for(int i = 0; i < transform.childCount; i++){
GameObject obj = transform.GetChild(i).GetComponent<Transform>().gameObject;
//do something with obj
}
在循環外聲明obj
gameObject會更有效,因為不再在循環的每次迭代中都重新創建變量。
另外,自Unity 5.5起, foreach
GC分配問題已經解決了常見集合問題,因此List<T>
類的集合不再分配,因此無需使用for
。
另一個調整將是更改以下內容:
obj = otherObj.GetComponent<Transform>().gameObject;
至:
obj = otherObj.gameObject;
對於從MonoBehaviour
派生的任何類, gameObject
和transform
都可用作屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.