Search Unity

Does allocating a NativeArray generate garbage?

Discussion in 'Entity Component System' started by Prodigga, Sep 27, 2019.

  1. Prodigga

    Prodigga

    Joined:
    Apr 13, 2011
    Posts:
    1,123
    Hi there

    I was watching the Converting your game to DOTS, here:


    And I noticed that for the spread ECS projectile spawning code, he was allocating a new NativeArray of entities with 20+ size every time the weapon fired. If this was Game object and Prefab land, you would want to reuse a list so that you aren't allocating a new list every time you fire.

    Is this not the case with native collections? Does this apply everywhere? IE I have some DOTS code that processes a list of meshes. Should I create one native array with the capacity to handle the maximum amount of verticies we will encounter in the list of Meshes, and reuse it in each iteration. Or should I just Release the native array at the end of each iteration and reallocate a new one for the next mesh?
     
  2. You need to Dispose all the Native* containers yourself. They won't be handled by the GC. This means it won't cause performance issues, but it also means that you do have to dispose them by hand otherwise you will end up with a decent memory leak.
     
    Prodigga likes this.
  3. Prodigga

    Prodigga

    Joined:
    Apr 13, 2011
    Posts:
    1,123
    Yes for sure! So since Native containers are structs, and I am handling the creation and disposal of the memory represented by the containers, there is no garbage collection issues in the traditional c# sense?
     
  4. TRS6123

    TRS6123

    Joined:
    May 16, 2015
    Posts:
    246
    If you have safety checks on, allocating a native container will generate some garbage due to the DisposeSentinel that Unity uses for the safety checks.
     
    Prodigga likes this.
  5. tertle

    tertle

    Joined:
    Jan 25, 2011
    Posts:
    3,761
    Should point out that this is only in the editor.
     
    BigRookGames and Prodigga like this.