简体   繁体   中英

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

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM