I have a function that gets a pointer to a array with size 4 (always) and must slice only the unique elements and return them. This function gets called 100k times a second thats why it needs to be fast and souldn't pressure the GC very much (thats why buffer variable is a pointer - stackalloc).
private const int BufferLength = 4;
private static unsafe ReadOnlySpan<int> SliceUnique(int* buffer)
{
// TODO: move the unique elements to the front
// and get the last unique index
return new ReadOnlySpan<int>(buffer, lastUniqueIndex + 1);
}
// Example:
// input: [1, 3, 2, 1] | [1, 4, 4, 4]
// output: [1, 3, 2] (order doesn't matter) | [1, 4]
Here is what I came up with (back when the question was about array of ints, but I'm sure it can be modified to handle
ReadOnlySpan<int>
(whatever that is...)).Tested on my computer, average execution time is 195 milliseconds for 1,000,000 arrays (including the creation of the arrays):
testing code: