Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to sort arrays without allocating any memory?

Tags:

c#

unity3d

I need to sort a rather big collection (high hundreds/low thousands of items) very frequently, that is every frame at 60 fps (I'm using Unity). Computing the key for each item is sort of slow so it needs to be cached.

I've tried various approaches:

  • List.Sort() with IComparer, computing the key every time: super slow
  • SortedList: MUCH faster, but generates GC allocs (30KB/frame): why? is they key boxed (I'm using a long)? is the key/value pair allocated? If I wrap the long in a class, the GC is halved, so my guess is "both": 1 alloc for the pair, one alloc to box the key if it's a value type...
  • Array.Sort(keyArray, valueArray): horrendous! slow & generates 256KB of GC/frame!

It's a shame because SortedList seemed perfect for the job, is there any GC-free alternative that I'm missing?

like image 494
benblo Avatar asked Sep 08 '14 17:09

benblo


People also ask

How can you sort an array without mutating the original array?

To sort an array, without mutating the original array:Call the slice() method on the array to get a copy. Call the sort() method on the copied array. The sort method will sort the copied array, without mutating the original.

Is sort () destructive?

sort() is a destructive process that sorts the original list in place.

How do you sort a big number array with limited memory?

Solution 1: step 1: Read M from the file and write it into a temp buffer. step 2: Sort (you should use in-place sorting algorithm, like QuickSort,HeapSort) the values. step 3: Create a temp file and write the buffer into the temp file.


1 Answers

If computing keys is so slow, you can add key property to your item class, calculate it before sorting, and then use your first method with IComparer simply comparing keys.

like image 181
Anton Savin Avatar answered Oct 20 '22 21:10

Anton Savin