Hello there, I am working with native containers and I am confused with allocators. I understand what they do, Temp lasts only 1 frame, TempJob up to 3 and Persistent indefinitely, but what confuses me is if the temporary allocators erase data stored in the list.
What I mean by that is that I have one list that I want to “re-do” every frame and I dont know if I can rely on just the temp allocator to erase the contents, or if I must also execute .Clear to erase the data. I also heard I must use .Dispose at the end of my usage for the container, can you confirm it/explain it as well?
Many thanks for answers.
(Edit: Jesus Christ I use “I” very, very often lmao)
Do temporary allocators erase data stored in the list ?
It’s generally your responsibility to do that but Allocator.Temp is an exception. So yes.
I also heard I must use .Dispose at the end of my usage for the container, can you confirm it/explain it as well?
Yes. Every NativeContainer requires you to call Dispose()directly or indirectly (jobs can schedule deallocation when completed). Exception to that is Allocator.Temp for which you can still do that but this is not required.
One of the ideas behind NativeContainer is to give us power to manually allocate memory C-like style. But this comes with responsibility to release that memory explicitly so there is no memory leaks.
I have one list that I want to “re-do” every frame and I dont know if I can rely on just the temp allocator to erase the contents, or if I must also execute .Clear to erase the data.
I suggest going with Allocator.Persistent here i.e. allocate once then reuse the same memory block while system is running:
public class MySystem : SystemBase
{
NativeList<int2> myPersistentList;
protected override void OnCreate ()
{
myPersistentList = new NativeList<int2>(
initialCapacity: 100 ,
allocator: Allocator.Persistent
);
}
protected override void OnDestroy ()
{
if( myPersistentList.IsCreated )
myPersistentList.Dispose( Dependency );
}
protected override void OnUpdate ()
{
myPersistentList.Clear();
var myListAlias = myPersistentList;// just an alias, nothing more
Job
.WithName("fill_list_job")
.WithCode( () =>
{
for( int i=0 ; i<100 ; i++ )
myListAlias.Add( new int2{ x=i , y=i } );
} )
.Schedule();
}
}