用null初始化局部变量是否会影响性能? [英] Does initialization of local variable with null impacts performance?

查看:81
本文介绍了用null初始化局部变量是否会影响性能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们比较两段代码:

String str = null;
//Possibly do something...
str = "Test";
Console.WriteLine(str);

String str;
//Possibly do something...
str = "Test";
Console.WriteLine(str);

我一直认为这些代码段是相同的。但是在我构建了这些代码(检查了优化的发布模式)并比较了生成的IL方法之后,我注意到第一个示例中还有另外两个IL指令:

I was always thinking that these pieces of code are equal. But after I have build these code (Release mode with optimization checked) and compared IL methods generated I have noticed that there are two more IL instructions in the first sample:

1st示例代码IL:

1st sample code IL:

.maxstack 1

.locals初始化([0]字符串str)

IL_0000:ldnull

IL_0001:stloc.0

IL_0002:ldstr测试

IL_0007:stloc.0

IL_0008:ldloc.0

IL_0009:调用void [mscorlib] System.Console :: WriteLine(string)

IL_000e:ret

.maxstack 1
.locals init ([0] string str)
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldstr "Test"
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: call void [mscorlib]System.Console::WriteLine(string)
IL_000e: ret

第二个示例代码IL:

.maxstack 1

.locals init( [0]字符串str)

IL_0000:ldstr测试

IL_0005:stloc.0

IL_0006:ldloc.0

IL_0007:调用void [mscorlib] System.Console :: WriteLine(string)

IL_000c:ret

.maxstack 1
.locals init ([0] string str)
IL_0000: ldstr "Test"
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: call void [mscorlib]System.Console::WriteLine(string)
IL_000c: ret

可能这段代码是由JIT编译器优化的吗?
那么使用null初始化本地bethod变量是否会影响性能(我知道这是非常简单的操作,但是无论如何),我们应该避免使用它吗?
预先感谢。

Possibly this code is optimized by JIT compiller? So does the initialization of local bethod variable with null impacts the performence (I understand that it is very simple operation but any case) and we should avoid it? Thanks beforehand.

推荐答案

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

总结一下,在运行各种基准测试之后,将对象初始化为值(作为定义的一部分,在类中)构造函数或作为初始化方法的一部分)在.NET 1.1和2.0上的速度大约慢10-35%。较新的编译器可以优化定义时的初始化。最后,建议您避免初始化作为一般规则。

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.

这篇关于用null初始化局部变量是否会影响性能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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