Home > front end >  Where is the reference variable in function loaded in memory between heap and stack?
Where is the reference variable in function loaded in memory between heap and stack?

Time:03-25

I've made a function to get "RectTransform" components from all child GameObjects of a parent GameObject.

using UnityEngine;

public class Test_Script : MonoBehaviour
{
    public GameObject parent_G;
    RectTransform[] child_R;

    private void Awake()
    {
        child_R = Get_ChildRectTransform(parent_G);
    }

    public RectTransform[] Get_ChildRectTransform(GameObject parent)
    {
        int sum_Child = parent.transform.childCount;
        RectTransform[] temporary_R = new RectTransform[sum_Child];
        for (int i = 0; i < sum_Child; i  )
            temporary_R[i] = parent.transform.GetChild(i).GetComponent<RectTransform>();
        return temporary_R;
    }
}

My question is... Is "temporary_R" in the Function loaded in Stack? And Is it terminated after the Function? Otherwise, is it going to be loaded in Heap as I wrote "new" and as "array"?

CodePudding user response:

temporary_R it a local variable that references to an array of RectTransform. The local variable is stored on the stack, and automatically "freed" when the function returns. Even if we typically do not talk about allocating/freeing local variables.

The actual RectTransforms are stored on the heap, either as part of the array-object if it is a value type/struct or or separately if it is a reference type/class. These objects will be released by the garbage collector whenever it gets around to it.

You would typically not worry about allocations like this. sum_Child will probably be fairly small, so the amount of memory should also be limited. And since it is only kept alive for a short duration it will most likely be collected in gen 0/1, i.e. the cheap kind of garbage collection. I would also assume it is run fairly infrequently, like once per frame.

You would typically only worry about memory allocation when allocating large objects (i.e. >~ 87kb), or allocating very frequently, like inside a tight loop. And even then it is usually a good idea to use a performance or memory profiler to check allocation rates, time spent in GC, etc to determine if it is a problem.

  • Related