簡體   English   中英

哪個變量聲明可以優化內存性能

[英]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派生的任何類, gameObjecttransform都可用作屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM