Search Unity

Resolved How to reduce garbage created by MeshGenerationContext.Allocate?

Discussion in 'UI Toolkit' started by _geo__, Jun 5, 2023.

  1. _geo__

    _geo__

    Joined:
    Feb 26, 2014
    Posts:
    1,336
    Is there a way to reduce the garbage created by calling MeshGenerationContext.Allocate?

    I have a dynamic mesh that changes every frame. I use
    OnGenerateVisualContent(MeshGenerationContext mgc)
    to draw it inside a visual element.

    According to the profiler there is quite some garbage created every frame due to the constant mesh reallocation by the MeshGenerationContext. It would be great to have some sort of native array to access and modify instead of reallocating the memory every frame. The number of vertices (about 400) I have remains constant but their positions and colors change a lot.

    I played around a bit with the ImmediateModeElement. But it's a bit cumbersome to use. Before I take that route I wanted to check if there is a way to do it with the normal MeshGenerationContext.

    Thank you.
     
  2. AlexandreT-unity

    AlexandreT-unity

    Unity Technologies

    Joined:
    Feb 1, 2018
    Posts:
    377
    You shouldn't have constant GC reallocation beyond 4-5 frames if you're just repainting one element. At that point, pools should be warmed up. Could you share a profiler capture?
     
    _geo__ likes this.
  3. _geo__

    _geo__

    Joined:
    Feb 26, 2014
    Posts:
    1,336
    Hi,

    I have uploaded them here:
    https://kamgam.com/unity/ShallowProfile.zip
    https://kamgam.com/unity/DeepProfile.zip


    Here is a screenshot of the deep profiling result:
    upload_2023-6-5_17-36-28.png

    To give a bit of context. I am reading the particles from a particle system and then for each I draw a single quad into the element. So at first the number of vertices increases but once it has reached saturation it stays the same.

    I just realized the actual Allocate() call shows 0 GC in this. So maybe probably, I was looking at the wrong part. I'll have to dig some further in my own code then. Sorry, my bad.

    UPDATE: Definitely was my own code. Thanks for the hint with the caches/pools. That got me unstuck.
     
    Last edited: Jun 5, 2023
  4. AlexandreT-unity

    AlexandreT-unity

    Unity Technologies

    Joined:
    Feb 1, 2018
    Posts:
    377
    No problem, you're welcome!
     
    _geo__ likes this.