静态构造函数会导致性能开销? [英] Static constructors cause a performance overhead?

查看:235
本文介绍了静态构造函数会导致性能开销?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近阅读一篇关于dotnetpearls.com的文章,这里说静态ctors需要大量的性能命中。

Recently read in a article on dotnetpearls.com here saying that static ctors take a substantial amount of perfomance hit.

难道不是为什么?

推荐答案

我认为实质性是多数用例中的多数。

I think "substantial" is an overstatement in most use cases.

有一个静态构造函数(即使它什么也不做)会影响类型初始化时间,因为 beforefieldinit标志。对于有静态构造函数的时序,有更严格的保证。

Having a static constructor (even if it does nothing) affects type initialization time due to the presence/absence of the beforefieldinit flag. There are stricter guarantees about timing when you have a static constructor.

对于大多数代码,我建议这没有什么区别 - 但如果你紧缩循环并访问类的静态成员,它可能。我个人不会太担心它 - 如果你有怀疑它在你的真实的应用程序相关,然后测试而不是猜测。 Microbenchmarks很可能会夸大这里的效果。

For most code, I'd suggest this doesn't make much difference - but if you're tight-looping and accessing a static member of a class, it might. Personally I wouldn't worry about it too much - if you have a suspicion that it's relevant in your real application, then test it rather than guessing. Microbenchmarks are very likely to exaggerate the effect here.

值得注意的是,.NET 4 与以前的版本有所不同涉及到类型初始化 - 所以任何基准应该真正显示不同的版本,以便相关。

It's worth noting that .NET 4 behaves somewhat differently to previous versions when it comes to type initialization - so any benchmarks should really show the different versions in order to be relevant.

这篇关于静态构造函数会导致性能开销?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆