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

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

问题描述

最近看了在dotnetpearls.com 这里的文章说,静态构建函数取性能比较命中一笔可观的。

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.

有关的的代码,我建议这并没有太大的差别 - 但如果你是紧循环和访问类的静态成员,它可能。个人而言,我不会担心太多 - 如果你有怀疑,这是有关你的真正的应用程序,然后对其进行测试,而不是猜测。微基准很可能在这里夸大的效果。

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的behaves有所不同,当涉及到输入初始化之前的版本 - 因此,任何基准测试应该真正表现出不同的版本为了是相关的。

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天全站免登陆