I'm working on a visualization that runs at 60fps. Part of that visualization is sorting the items on screen based on their position. I'm using
Array.Sort<T>(T[] array, int index, int length, IComparer<T> comparer)
which is allocating almost 1MB of Comparison<T> per second, which causes the GC to run frequently, which causes framerate hiccups.
I've tried several variations of Array.Sort and they're all allocating, including the one that accepts Comparison<T> (which is also insufficient because it lacks index and length parameters).
Is there any way to sort an array in C# (.NET 5) without allocating large amounts of memory?
Update: Here's a repro,
using System;
using System.Collections.Generic;
namespace New_folder
{
public class EmptyClass
{
// Empty
}
public class EmptyClassComparer : IComparer<EmptyClass>
{
public int Compare(EmptyClass x, EmptyClass y)
{
return 0;
}
}
class Program
{
static void Main(string[] args)
{
EmptyClass[] emptyClasses = new EmptyClass[100];
for (int i = 0; i < 100; i++)
{
emptyClasses[i] = new EmptyClass();
}
EmptyClassComparer emptyClassComparer = new EmptyClassComparer();
while (true)
{
Array.Sort(emptyClasses, 0, 50, emptyClassComparer);
}
}
}
}
and the allocations after 30 seconds on an old machine,
