Unity: What's allocating memory in my function?

Viewed 761

I am relatively new to memory and optimization. I was tasked to optimize an existing project and while looking at the profiler in Unity, I saw that there was a function producing a bunch of stuff for the GC to clean up.

The function is as such:

public bool AnyCanvasOpen()
{
    for (int i = 0; i < canvasList.Count; i++)
        if (canvasList[i].activeSelf && canvasList[i].name != "MainUICanvas")
            return true;

    return false;
}

where canvasList is just a list of GameObjects. What could be the cause of my 282B allocation?

1 Answers

The canvasList variable is a List of GameObject and Unity's GameObject derives from UnityEngine.Object which has the name property you are using.

The memory allocation came from that: canvasList[i].name != "MainUICanvas"

This is because the Object.name property needs to return a string from the native side and this means that a new string is created each time that property is accessed. This is why the GameObject.CompareTag function was added, to make it possible to compare Object name without allocation memory. The GameObject.CompareTag function will compare the object name on the native side without the need to create or return a new string on the C# side. This removes the memory allocation.

Unfortunately, most Unity code examples on their site and elsewhere uses Object.name instead of the GameObject.CompareTag function which causes more people to use the Object.name property more often.

This shouldn't allocate memory:

List<GameObject> canvasList = new List<GameObject>();

public bool AnyCanvasOpen()
{
    for (int i = 0; i < canvasList.Count; i++)
        if (canvasList[i].activeSelf && canvasList[i].CompareTag("MainUICanvas"))
            return true;

    return false;
}
Related