Does initialization of local variable with null impacts performance?

南笙酒味 提交于 2019-12-04 04:36:58
JonSG

http://www.codinghorror.com/blog/2005/07/for-best-results-dont-initialize-variables.html

To summarize from the article, after running various benchmarks, initializing an object to a value (either as part of a definition, in the class' constructor, or as part of an initialization method) can be anywhere from roughly 10-35% slower on .NET 1.1 and 2.0. Newer compilers may optimize away initialization on definition. The article closes by recommending to avoid initialization as a general rule.

It is slightly slower, as Jon.Stromer.Galley's link points out. But the difference is amazingly small; likely on the order of nanoseconds. At that level, the overhead from using a high-level language like C# dwarfs any performance difference. If performance is that much of an issue, you may as well be coding in C or ASM or something.

The value of writing clear code (whatever that means to you) will far outweigh the 0.00001ms performance increase in terms of cost vs. benefit. That's why C# and other high-level languages exist in the first place.

I get that this is probably meant as an academic question, and I don't discount the value of understanding the internals of the CLR. But in this case, it just seems like the wrong thing to focus on.

Today (2019) both the .NET Framework and the .NET Core compilers are smart enough to optimize unneeded initializations away. (Along with the useless stloc.0 - ldloc.0 pair.)

Both versions compile as

        .maxstack 8

        ldstr "Test"
        call void [System.Console]System.Console::WriteLine(string)
        ret

See my SharpLab experiment as reference.

But of course implementations change, but Justin's answer is timeless: I did this experiment out of curiosity, in a real situation focus on code clarity and expressiveness, and ignore micro-optimizations.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!