Aliasing allocators
Use aliasing to share memory allocations between collections in Unity Collections.
Read time 2 minutesLast updated 6 days ago
An alias is a collection that doesn't have its own allocation but instead shares the allocation of another collection, in whole or in part. For example, you can use to create a that aliases the . Writing to the writes to the and vice-versa, but resizing the invalidates the alias.
NativeList.AsArrayNativeArrayNativeListNativeArrayNativeListNativeListNativeArrayYou don't need to dispose aliases, and calling on an alias does nothing. Once an original is disposed, you can no longer use the aliases of the original:
DisposeNativeList<int> nums = new NativeList<int>(10, Allocator.TempJob); nums.Length = 5; // Create an array of 5 ints that aliases the content of the list. NativeArray<int> aliasedNums = nums.AsArray(); // Modify the first element of both the array and the list. aliasedNums[0] = 99; // Only the original need be disposed. nums.Dispose(); // Throws an ObjectDisposedException because disposing // the original deallocates the aliased memory. aliasedNums[0] = 99;
Aliasing is useful for the following situations:
- Getting a collection's data in a way that exposes fewer capabilities: for example, a alias removes the ability to resize, which you might want to reserve for particular circumstances.
NativeArray - Getting a view into existing memory that is either a subset of another collection or is part of no collection at all.
- Array reinterpretation.
An collection can alias a collection even though such cases undermine the safety checks. For example, if an aliases a , it's not safe to schedule a job that accesses one while another job is also scheduled that accesses the other, but the safety checks don't catch these cases. This is why such collections are called .
Unsafe-Native-UnsafeListNativeListUnsafeArray reinterpretation
A reinterpretation of an array is an alias of the array that reads and writes the content as a different element type. For example, a which reinterprets a shares the same bytes, but it reads and writes the bytes as values instead of values. Because each is 4 bytes while each is 2 bytes, each corresponds to two shorts, and the reinterpretation has twice the length of the original.
NativeArray<short>NativeArray<int>shortintintshortintThe following example demonstrates this:
NativeArray<int> ints = new NativeArray<int>(10, Allocator.Temp); // Length of the reinterpreted array is 20 // (because it has two shorts per one int of the original). NativeArray<short> shorts = ints.Reinterpret<int, short>(); // Modifies the first 4 bytes of the array. shorts[0] = 1; shorts[1] = 1; int val = ints[0]; // val is 65537 (2^16 + 2^0) // Like with other aliased collections, only the original // needs to be disposed. ints.Dispose(); // Throws an ObjectDisposedException because disposing // the original deallocates the aliased memory. shorts[0] = 1;