C# How Can I Sort A List without Generating Any Garbage at All (Unity3d)

Viewed 668

The method used by List.Sort ends up using Array.Sort which generates 2 bytes of garbage even if you pass in an instance for IComparer. I need to sort many lists every frame in Unity3d so I need an algorithm that will not create a single byte of garbage if possible. Stack allocation for temporary variables should be fine.

Unity Profiler Pic

if (comparer == null)
    comparer = (IComparer<T>)Comparer<T>.Default;
if (BinaryCompatibility.TargetsAtLeast_Desktop_V4_5)
    ArraySortHelper<T>.IntrospectiveSort(keys, index, length, comparer);
else
    ArraySortHelper<T>.DepthLimitedQuickSort(keys, index, length + index - 1, comparer, 32);
1 Answers

Check out this library in this github repo. I found this in bottom in this article which is about how LINQ affects GC and which LINQ function is safe to use on every frame. This library is written especially for unity and as author says this library is

A no-GC version of C#'s IEnumerator and LINQ

There is sort method which implements quickSort algorithms and does not produce garbage. To be honest I don't fully tested it yet, but as much as I used that it works finely.

Related