7

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?

0

2 Answers 2

22

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.

Sign up to request clarification or add additional context in comments.

1 Comment

That explains so much, thank you! I will have to retry it with the optimizing enabled.
6

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

5 Comments

It is, ArraySortHelper<>.QuickSort was written in C#.
I suspect native methods are not used. There's not that much performance benefit in native code for swapping object references in an array, and there's no benefit on the comparison side since it's delegated to the appropriate Comparer method. An interesting exercise would be to compare the performance of the Mono's implementation of the BCL's List<T>.Sort() method to the MS.NET version. If they have similar performance characteristics, just look at the Mono code.
Thanks, @ja72 The best free tool since recently. The ReSharper guys just released their own, free tool dotPeek, too.
@Uwe - Well that didn't take long.. :-)
@Uwe Keim .. I didn't know that exactly as I wrote the comment, I just assumed there is no native code involved. That would impose strict limitations when using Array.Sort in environments with limited access to resources with probably no gain in performance. My comment was meant more ironically - people should start to understand that the assumption "native code is faster than managed code" does not hold automatically...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.