C# 调用方法时的预热
我刚刚发现这篇文章讨论了时间测量。我记得(希望我没有记错)如果这个方法以前从未被调用过,那么这是一种不公平的竞争。那就是:
// At the beginning of the application
MyClass instance = new MyClass();
instance.MyMethod();
instance.MyMethod(); // Faster than the first call, because now it's warmed up.
我们在C#中真的有这样的热身理论吗?如果是,为什么(CLR 在预热时会做什么)?如果这个方法是扩展方法(静态方法),一切都一样吗?
I just came across this post that talks about time measuring. I remember (I hope I'm not misremembering) it's an unfair competition, if this method is never called before. That is:
// At the beginning of the application
MyClass instance = new MyClass();
instance.MyMethod();
instance.MyMethod(); // Faster than the first call, because now it's warmed up.
Do we really have such warming-up theory in C#? If yes, why (what will the CLR do when warming-up)? And is everything the same if this method is an extension one (a static one)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果通过“预热”您指的是 JIT'ing,那么是的 - 如果一个方法从未被调用过,那么它还没有被编译,所以第一次运行它时它可能会更慢。
另请参阅 .NET CLR JIT 是否编译每个方法,每次?
If by "warm up" you refer to JIT'ing then yes - if a method is never called it won't have been compiled yet, so the very first time you run it it might be slower.
Also refer to Does the .NET CLR JIT compile every method, every time?
这是由于即时 (JIT) 编译造成的。如果您想提高性能并避免这种影响,本机图像生成器< /a> (Ngen.exe) 可以帮助你。
This is due to just-in-time (JIT) compilation. If you want to improve performance and avoid this effect, the Native Image Generator (Ngen.exe) can help you.
人们在这里谈论的是即时编译。您在 .NET 中创建的代码以中间语言存储,该中间语言与平台无关。当您运行 CIL 代码的应用程序部分时,会编译为特定于平台的指令,该指令需要第一次需要一点时间。然后它会被缓存,以便下次调用该方法时不会有这次时间损失。
如果您确实愿意,您可以预编译到特定于平台的版本。
What people are talking about here is just-in-time compilation. The code you create in .NET is stored in intermediate language, which is platform independent. When you are running the application parts of the CIL code are compiled to platform-specific instructions which takes a bit of time the first time around. Then it gets cached so the next time you call the method you don't have this time loss.
If you really want to, you can pre-compile to platform specific versions though.
它需要编译,这就是第一次调用时间较长的原因。
来自将 MSIL 编译为本机代码< /em>:
It needs to be compiled, and that is why the first call is longer.
From Compiling MSIL to Native Code: