Search Unity

Best patterns for disposing of temporary containers

Discussion in 'Entity Component System' started by jdtec, Nov 1, 2018.

  1. jdtec

    jdtec

    Joined:
    Oct 25, 2017
    Posts:
    302
    I've seen two ways of doing this so far.

    1) Declaring the nativeContainer variable as a system member so that you can dispose at the start of the next frame. eg.

    OnUpdate (jobHandle)
    {
    if (nativeContainer.Dispose) {nativeContainer.Dispose ();}
    nativeContainer.Allocate ();
    ScheduleJobsWithNativeContainer ();
    }

    2) Use the [DeallocateOnJobCompletion] attribute but this only works with NativeArrays which limits it considerably. It also requires making a job describing each array type input, which is more boilerplate.

    Are there any other methods I've missed? It would be nice to have some sort of allocate and dispose once job is complete for any Disposable type to save a lot of generic typing?
     
  2. tertle

    tertle

    Joined:
    Jan 25, 2011
    Posts:
    3,761
    Usually you just reuse other native containers rather than disposing of them every frame.

    Most (all?) are capacity resizable if required so there's not a lot of point to dispose of them every frame if you need them constantly.
     
  3. Attatekjir

    Attatekjir

    Joined:
    Sep 17, 2018
    Posts:
    23
    Do not forget to also dispose the nativeContainer in OnStopRunning when using method 1, so the container is also disposed when OnUpdate is no longer being called.

    Code (CSharp):
    1.     protected override void OnStopRunning()
    2.     {
    3.         if (nativeContainer.isCreated)
    4.         {
    5.             nativeContainer.Dispose();
    6.         }
    7.     }
     
    thelebaron likes this.
  4. jdtec

    jdtec

    Joined:
    Oct 25, 2017
    Posts:
    302
  5. tertle

    tertle

    Joined:
    Jan 25, 2011
    Posts:
    3,761
    Well you can't resize a native array but they can be disposed via pattern.

    But you can increase the size of a NativeHashMap.

    Capacity {get; set; }


    Note: you can not shrink them, only enlarge.
     
  6. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,770
    Actually this solve my issue.
    Thx for asking ;)