Webgl Memory Profiling

Hello, we’re facing issues with Webgl memory handling, so i did few tests

  1. First test was to create a 20 mgb byte array and then set it to null and do a GC.Collect but when doing profiling in chrome Inspector the memory kept increasing until it reached out of memory exception and crashed, did some research it mentioned that on webgl unity doesnt unload memory using GC.Collect
  2. Downloaded a texture and did a profile and it showed an increase in memory, then did an unload and did a profile the memory stayed the same it didnt decrease, but when i loaded the texture again it didnt increase
  3. Downloaded 200 mgb of asset bundle content ( Meshes and Prefabs ), did a profile, then unloaded, the memory stayed the same, but after that i downloaded textures and did a profile and the memory increased, it reached about the combined sum of the bundle content and the textures. But after that if i load or unload it doesnt change for both cases
  4. While researching it said that unity cleans memory when unloading a scene so i setup a scene and added it additively, memory increased, then unloaded the scene and memory stayed the same

Is there a way to better profile webgl to get more accurate data because it seems that inspector profiling isnt showing accurate results, or webgl doesnt free memory when it gets reserved and it only can overwrite it with the same type of content?
chrome_xpAgTYCIpq

Hi,

there are two limitations at play with Memory Management on the Web platform:

  1. The garbage collector can only run between frames so lots of temporary allocations will bump the used memory.
  2. The WebAssembly API only allows to grow the memory but not to shrink it.

If code does many temporary allocations within a single frame it can cause the WebAssembly heap to grow without any way to reclaim the memory. The only way to fix this is to avoid this kind of allocation and for example try to reuse memory used for temporary variables, use API such as List<T>.ReserveCapacity() to preallocate memory, use stack-allocated data structures(e.g. by using structs), etc.

You can refer to this page for more information: Unity - Manual: Memory in Unity Web

Regarding profiling the memory usage: The browser memory profiling will only be able to show how large the overal WebAssembly heap is but not how much of it is currently used. You can use the " Diagnostic Overlay" instead that can be enabled for a build in Player Settings > Publishing Settings > Show Diagnostics Overlay.

1 Like