简体   繁体   English

C# 中的 Array.Sort 怎么这么快?

[英]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.嘿,我一直在试图找到一个答案(在 stackoverflow 和 google 上),以解决 C# 中的 Array.Sort 如何如此之快的问题。 I didn't find one.我没有找到一个。

No matters which algorithm I used I didn't manage to sort big arrays faster than it.无论我使用哪种算法,我都无法比它更快地对大 arrays 进行排序。 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#.它是标准的快速排序代码,用 C# 编写。 You can find it in ArraySortHelper<>.QuickSort with, say, Reflector.你可以在 ArraySortHelper<>.QuickSort 中找到它,比如 Reflector。

A pretty standard mistake when profiling code is to do so with the JIT optimizer disabled.分析代码时的一个非常标准的错误是在禁用 JIT 优化器的情况下这样做。 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.当您分析 Array.Sort() 方法时不会发生这种情况,当 .NET 安装在您的机器上时,它是由 ngen.exe 预先设置的。 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".然后工具+选项,调试,常规,取消勾选“在模块加载时抑制JIT优化”。 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.您可以使用ILSpy反汇编代码。 I would expect native methods in the inner sorting code to speed up things.我希望内部排序代码中的本机方法可以加快速度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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