Allow setting mesh arrays with NativeArrays.

I did something similar except I extended it and created my own UnsafeNativeArray to completely avoid having to do any copy.

Here are some performance comparisons

Default NativeArray.CopyTo (2.40ms)

Array.CopyTo - very similar to Marshal performance (0.15ms)
Similar approach to @LennartJohansen , much much faster compared to default implementation

My custom UnsafeNativeArray - directly editing the array, no copying (0.07ms)

So relative performance between Array.Copy and directly editing array isn’t huge, however it does halve your memory requirement as you don’t require 2 copies of the array - not a big deal if you only need a single array but if you need a lot it’s signficant.

If anyone wants to try my UnsafeNativeArray, I’ve uploaded it here: https://github.com/tertle/UnsafeNativeArray

It works basically the same as NativeArray (90% of the code is identical) except you pass it an array in the constructor. It includes the same checks. It’s not safe because there are no checks on using the array you pass in. You must complete the job before using this array otherwise you’ll run into trouble.

var array = new int[30];
var unsafeNativeArray = new UnsafeNativeArray<int>(array);

var job = new Job
{
    UnsafeNativeArray = unsafeNativeArray; // use UnsafeNativeArray just like a NativeArray
}.Schedule();

job.Complete(); // make sure job is complete before using array

// Use array how you like, no need to copy result as UnsafeNativeArray just directly modifies the array

-edit-
one thing to note is you can’t use a 0 length array with UnsafeNativeArray, will throw an exception.

4 Likes