0

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.

huhyuh
  • 15
  • 1
  • 5
  • What about this question is not explained [here](https://learn.microsoft.com/en-us/dotnet/api/system.array.copy?view=net-5.0) where it says: "Copies a range of elements from an Array starting at the specified source index and pastes them to another Array starting at the specified destination index. The length and the indexes are specified as 64-bit integers." ? – Luuk Mar 06 '21 at 16:10
  • Or, do I miss something? Will removing these first 3 elements boost performance? – Luuk Mar 06 '21 at 16:11
  • it is technically possible to access the array via pointers using unsafe code. Tho at this point the question should really be, is C# the language you should be using given your problem. – Vulpex Mar 06 '21 at 16:14
  • @Luuk i want to avoid copying, which is what i am currently doing. – huhyuh Mar 06 '21 at 16:30
  • @Vulpex there is no other way, this integrates into a c# framework. I may actually be able to hack it because the data is strings, so i can implement a base64 conversion that uses an index. – huhyuh Mar 06 '21 at 16:31
  • Seems like you should modify your copying code with a switch or parameter, rather than the array. Or maybe just make a different function/method for copying from a different offset. Hard to say for sure though since we haven't seen any code yet. – RBarryYoung Mar 06 '21 at 16:40
  • You could override the get/set, like shown [here](https://stackoverflow.com/questions/43485128/get-set-accessors-for-array-property-with-index-handled) and ignore the first 3 elements. Then no copying is needed? – Luuk Mar 06 '21 at 16:44
  • I suggest you look at this problem a different way. Instead of needing a new array, perhaps you need an object that represents a window into the existing array. So write a wrapper class that maps logical index onto physical index. – John Wu Mar 06 '21 at 18:11

1 Answers1

1

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

Genusatplay
  • 761
  • 1
  • 4
  • 15