简体   繁体   English

编译器评估显式null-check与null-coalescing运算符?

[英]Compiler evaluation of explicit null-check vs. null-coalescing operator?

Consider the following code, which uses two slightly different methods to check _instance and assign it when not already set. 请考虑以下代码,该代码使用两种略有不同的方法来检查_instance并在尚未设置时分配它。

class InstantiationTest
{
    private Object _instance;

    public void Method1() {
        if(_instance == null) {
            _instance = new Object();
        }
    }

    public void Method2() {
        _instance = _instance ?? new Object();
    }
}

Either VS or Resharper keeps underlining my explicit null checks, and prompting me to refactor using the null-coalescing operator. VS或Resharper不断为我的显式空检查加下划线,并提示我使用null-coalescing运算符进行重构。

I wondered whether the compiler is smart enough to detect the case in Method2() where _instance is reassigned to itself (effectively a nop ?) and rewrite Method2() into Method1() . 我不知道该编译器是否足够聪明来检测的情况下, Method2()其中_instance重新分配给自己(实际上是一个NOP ?)和重写Method2()Method1()

I see this is not actually the case: 我看到实际情况并非如此:

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   

versus: 与:

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      

My question is why ? 我的问题是为什么

Is it tricky to implement at the compiler level, too trivial to be worth the effort of implementation, or something I'm missing? 在编译器级别实现是否棘手,是否值得实现的努力是微不足道的,或者我缺少的东西?

Generally, the C# compiler does very little optimizing of the IL, leaving that up to the JIT, which optimizes things much better for a specific architecture. 通常,C#编译器对IL的优化很少,只能将其归结为JIT,这样可以更好地优化特定体系结构。 So it's simply not been implemented within the compiler, as that would take time away from other things. 所以它根本没有在编译器中实现,因为这需要时间远离其他事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM