考虑下面的代码,它使用了两个slightly不同的检查方法_instance
并在尚未设置时分配它。
class InstantiationTest
{
private Object _instance;
public void Method1() {
if(_instance == null) {
_instance = new Object();
}
}
public void Method2() {
_instance = _instance ?? new Object();
}
}
VS 或 Resharper 不断强调我的显式空检查,并提示我使用空合并运算符进行重构。
我想知道编译器是否足够聪明来检测这种情况Method2()
where _instance
被重新分配给自身(实际上是nop http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.nop.aspx?)并重写Method2()
into Method1()
.
我发现实际情况并非如此:
Test.Method1:
IL_0000: ldarg.0
IL_0001: ldfld UserQuery+Test._instance
IL_0006: brtrue.s IL_0013
IL_0008: ldarg.0
IL_0009: newobj System.Object..ctor
IL_000E: stfld UserQuery+Test._instance
IL_0013: ret
相对:
Test.Method2:
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: ldfld UserQuery+Test._instance
IL_0007: dup
IL_0008: brtrue.s IL_0010
IL_000A: pop
IL_000B: newobj System.Object..ctor
IL_0010: stfld UserQuery+Test._instance
IL_0015: ret
我的问题是why?
在编译器级别实现是否很棘手,是否太微不足道,不值得付出努力,或者我缺少什么?
一般来说,C# 编译器很少对 IL 进行优化,而将其留给 JIT,JIT 可以更好地针对特定体系结构进行优化。所以它根本没有在编译器中实现,因为这会占用其他事情的时间。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)