I have an array with total 5000 elements and at one functionality, I only need last 3000 elements only to proceed further.
for that I have tried following solution.
//skipping first 2000 elements
list = list.Skip(5000 - 3000).ToArray();
This solution is actually giving me desired solution, but when I ran profiler on my code, It is showing huge amount memory allocation on this line.
I have to use Array only due to carried on legacy. and very frequent ToArray()
doesn't seem to be good for performance.
there is also possible solution,
//reversing whole list
Array.Reverse(list);
//restricting size of an array to 3000,
//so first (as reversed the list, they are last 3000 elements)
Array.Resize(ref list, 3000);
//again reversing list to make it proper order
Array.Reverse(list);
but this is even worse in time complexity.
Is there any better solution for this, which doesn't need casting from List to Array ?
If you absolutely have to use an array, then Array.Copy
is probably your friend:
int[] smallerArray = new int[array.Length - 2000];
Array.Copy(array, 2000, smallerArray, 0, smallerArray.Length);
I'd expect that to be a bit more efficient than using Take
followed by ToArray
.
See more on this question at Stackoverflow