- Home /
Can I store a NativeArray instance by reference?
Hey. I want to save a NativeArray for later use. However what I don't want is unnecessary memory copies. Since NativeArray is a struct it will get copied by default rather than being passed by reference. I tried default ways from Microsoft documentation but it didn't seem to work. I wonder if it's even possible?
Thanks
Answer by andrew-lukasik · May 03, 2020 at 10:26 PM
Yes, Allocator.Persistent
is for long-term data storage cases.
You absolutely need to know here that although NativeArray
is a struct
it doesn't contain it's data but a mere pointer to an actual memory allocation.
So - copying and passing that struct around won't produce any overhead.
Note: When you call
Dispose()
on one of the collection struct copies the other copies will have no data about it and will throw an exception when this is repeated, stating that this allocation was deallocated already. To make sure this doesn't happen try to limit yourself to a single copy or figure out a scheme that takes care of that.
Answer by jasons-novaleaf · Jan 04, 2021 at 02:52 PM
I am new to DOTS but I think andrew's answer is inaccurate.
NativeArray doesn't store the data, but stores a reference to the data. Changing the Allocator just changes where that data is stored, not anything about the NativeArray itself.
If you want to get a "reference" to the data, you can use an unsafe pointer, which works even if you use Allocator.Temp. see Unity.Collections.LowLevel.Unsafe.NativeArrayUnsafeUtility.GetUnsafeReadOnlyPtr()
NativeArray (...) stores a reference to the data.
If you look into it's source code, NativeArray
is really just
void* m_Buffer;
int m_Length;
with dozens of utility and safety methods around it. So I don't see how copying it is of no much bigger consequence that copying an int3
.
Changing the Allocator just changes where that data is stored, not anything about the NativeArray itself.
Yes. Also for how long it can be allocated.
Your answer
Follow this Question
Related Questions
NativeList Empty Outside Job But Not Inside It 1 Answer
Sub-emitter memory leak? 3 Answers
Memory usage of Sprites in a referenced Scriptable Object 0 Answers
How to optimize memory usage in webgl applications 0 Answers
How come memory usage is so high on Linux, and the profiler lies about it? 1 Answer