Most efficient way of getting the N last element of an array
arrays, c#, linq, performance
Solution
From the comments:
public static T[] TakeLast<T>(this T[] inputArray, int count)
{
var result = new T[count];
Array.Copy(inputArray, inputArray.Length - count, result, 0, count);
return result;
}
seems to perform well. It's worth pointing out that depending on the specific needs, it may be possible to avoid the new array altogether, and iterate over the original `inputArray`. You can't copy faster than not copy at all. :)
Problem
For a project, I will have to take very often the N last element of an array containing a lot of data. I tried to make ``` myArray.Skip(myArray.Length - toTake).Take(toTake) ``` But I found it slow. I compared it to this: ``` public static int[] TakeLast(this int[] inputArray, int count) { int[] returnArray = new int[count]; int startIndex = Math.Max(inputArray.Count() - count, 0); unsafe { fixed (int* itemArrayPtr = &(inputArray[startIndex])) { fixed (int* arrayPtr = &(returnArray[0])) { int* itemValuePtr = itemArrayPtr; int* valuePtr = arrayPtr; for (int i = 0; i < count; i++) { *valuePtr++ = *itemValuePtr++; } } } } return returnArray; } ``` This works well be this cannot be generic(I wish this could work for any primitive type(int, float, double, ...). Is there a way to achieve a comparable performance having a generic/linq/... method? I don't need to make it works on IEnumerable, Array is enough for me. EDIT I'm currently testing all methods you gave me, for now it's the Array.Copy which seems to be the faster: ``` Generating array for 100000000 elements. SkipTake: 00:00:00.3009047 Unsafe: 00:00:00.0006289 Array.Copy: 00:00:00.0000012 Buffer.BlockCopy: 00:00:00.0001860 Reverse Linq: 00:00:00.2201143 Finished ```