Tengku Fathullah
Tengku Fathullah

Reputation: 1370

Which variable declaration optimize memory performance

Which method optimize memory or is it same ?. Does GameObject of Method 1 create a new memory allocation for every loop ?, since I believe GameObject of Method 2 using the same memory reference.

Does Method 1 create GC or create new memory allocation that will reduce performance ?

Method 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
}

Method 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
}

Upvotes: 1

Views: 573

Answers (2)

user967853
user967853

Reputation:

Declaring obj gameObject outside the loop will be more performant as the variable no longer gets recreated on every iteration of the loop.

Also since Unity 5.5, the foreach GC alloc issue, has been resolved for common collections, so collections like List<T> no longer allocate, so there is no need to use for.

Another adjustment would be to change the following:

obj = otherObj.GetComponent<Transform>().gameObject;

To:

obj = otherObj.gameObject;

Both gameObject and transform are available as properties for any class deriving from MonoBehaviour.

Upvotes: 0

izeed
izeed

Reputation: 1731

GC stress of both methods is the same. The culprit is not the obj but rather the foreach. If you iterate using for, you can do this loop without any memory allocation:

for(int i = 0; i < transform.childCount; i++){
        GameObject obj = transform.GetChild(i).GetComponent<Transform>().gameObject;
        //do something with obj
    }

Upvotes: 1

Related Questions