huhyuh
huhyuh

Reputation: 15

C# modifying array to change the starting position

I have a function that does work on an array, and the first 4 bytes are reserved for instructions. After the operations, the result lies from index 3 to the end. I am currently creating another array and copying from element 4 to the end.

Is there any way to modify the array (possibly using unsafe code) in order to change the starting location / resize? This would remove the copying and allocation and massively boost performance. There is Array.Resize, but it is not what i am looking for.

Upvotes: 0

Views: 600

Answers (1)

Genusatplay
Genusatplay

Reputation: 771

You can use Span<T> to represent data without copying the array.

var testData = new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
var result = new Span<byte>(testData).Slice(3);
//result -> {3, 4, 5, 6, 7, 8, 9, 10}

https://learn.microsoft.com/en-us/archive/msdn-magazine/2018/january/csharp-all-about-span-exploring-a-new-net-mainstay

Upvotes: 1

Related Questions