WebGL free managed heap memory

Hi guys,

Is GC.Collect() not working in WebGL?
I have a case like this :

        Debug.Log(string.Format("TotalMemory #0 : {0}", GC.GetTotalMemory(false)));
        using (var www = new WWW(path))
        {
            yield return www;

            var data = www.bytes;

            Debug.Log(string.Format("TotalMemory #1 : {0}", GC.GetTotalMemory(false)));

            data = null;

            GC.Collect();
            GC.WaitForPendingFinalizers();

            Debug.Log(string.Format("TotalMemory #2 : {0}", GC.GetTotalMemory(false)));
        }

In editor, TotalMemory #2 certainly less than #1, which indicates the memory being freed. But, in WebGL, the value in TotalMemory #2 is the same as TotalMemory #1 (memory not being freed).

Can anyone explain why is that? And what do I need to do to free the data in WebGL?

Sorry I missed this question.

Calling GC.Collect() via scripting has no effect on Unity WebGL. This is because we can’t garbage collect when the call stack is not empty. More details about this limitation can be found in the manual.
At the moment, Unity WebGL will try to perform some garbage collection at the beginning of every frame. Then when a new scene is loaded, a full garbage collection is performed.

1 Like