Does allocating a NativeArray generate garbage?

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?

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.

1 Like

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?

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.

1 Like

Should point out that this is only in the editor.

2 Likes