Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is Array.Sort in C# so super-fast?

Tags:

c#

sorting

Hey, I have been trying to find an answer (both on stackoverflow and google) to the question how Array.Sort in C# is so fast. I didn't find one.

No matters which algorithm I used I didn't manage to sort big arrays faster than it. I know it uses Quick Sort, but it must be very optimized.

Does anybody know how did they make it so fast?

like image 288
Shay Ben Moshe Avatar asked May 28 '11 14:05

Shay Ben Moshe


Video Answer


2 Answers

It is standard quicksort code, written in C#. You can find it in ArraySortHelper<>.QuickSort with, say, Reflector.

A pretty standard mistake when profiling code is to do so with the JIT optimizer disabled. Which will happen when you run the Debug build or have a debugger attached. This won't happen when you profile the Array.Sort() method, it was pre-jitted by ngen.exe when .NET was installed on your machine. The optimizer has a great affect on the quality of the generated machine code. Check this answer for the kind of optimizations it performs.

You can debug release quality machine code but that requires changing an option. First switch to the Release configuration. Then Tools + Options, Debugging, General, untick "Suppress JIT optimization on module load". Beware of the pitfalls, you'll see the effects of inlining, code hoisting and elimination of local variables.

like image 149
Hans Passant Avatar answered Oct 22 '22 02:10

Hans Passant


You could use ILSpy to disassemble the code. I would expect native methods in the inner sorting code to speed up things.

like image 40
Uwe Keim Avatar answered Oct 22 '22 02:10

Uwe Keim