更新时间:2022-06-14 23:15:08
我比较了生成代码的CIL(确保执行发布版本-在项目属性中选中优化代码",这与/optimize
相对应)开启csc.exe
).这就是我得到的(使用VS 2008-注意Foo.MaybeFoo()
是一种有时会返回null
有时是Foo
的方法)
I compared the CIL of the generated code (making sure to do a Release build - with Optimize Code checked in the Project Properties, which corresponds to the /optimize
switch on csc.exe
). This is what I got (using VS 2008 - note that Foo.MaybeFoo()
is a method that sometimes returns null
, sometimes a Foo
)
GetFooWithIf
:
IL_0000: call class Application3.Foo Application3.Foo::MaybeFoo()
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: brtrue.s IL_000f
IL_0009: newobj instance void Application3.Foo::.ctor()
IL_000e: stloc.0
IL_000f: ldloc.0
IL_0010: ret
GetFooWithCoalescingOperator
:
IL_0000: call class Application3.Foo Application3.Foo::MaybeFoo()
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: dup
IL_0008: brtrue.s IL_0010
IL_000a: pop
IL_000b: newobj instance void Application3.Foo::.ctor()
IL_0010: stloc.0
IL_0011: ldloc.0
IL_0012: ret
因此,除了额外的堆栈顶部复制和弹出操作外,其他操作均相同.如果可以通过这种方式来显着改善性能,我将专门购买帽子以供食用.因此,请选择您认为具有更好可读性的代码.
Thus, the same except for an extra top-of-stack-duplication and pop. If this can be made to make a measurable performance difference, I will purchase a hat specifically for the purpose of eating it; therefore, go with the one that you feel offers better readability.
(编辑)哦,准时器可能足够聪明,甚至可以消除这种差异!
(edit) oh, and the JITter might be clever enough to get rid of even that difference!