Best patterns for disposing of temporary containers

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 ();
}

  1. 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?

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.

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.

    protected override void OnStopRunning()
    {
        if (nativeContainer.isCreated)
        {
            nativeContainer.Dispose();
        }
    }
1 Like

Can you resize hashmaps or nativearrays?

I’m finding a similar pattern as shown in the boids example at the moment to work best for me.

https://github.com/Unity-Technologies/EntityComponentSystemSamples/blob/master/Samples/Assets/GameCode/Samples.Boids/BoidSystem.cs

It does sound correct to simply reuse when that’s possible though.

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.

Actually this solve my issue.
Thx for asking :wink: