gpt4 book ai didi

c# - Null-Conditional 运算符是否在连续使用站点之间进行了优化,还是会导致重复检查?

转载 作者:太空狗 更新时间:2023-10-29 18:14:47 24 4
gpt4 key购买 nike

是否使用空条件运算符重复空检查?例如

var x = instance?.Property1;
var y = instance?.Property2;

是否将其编译成:

if (instance != null)
{
var x = instance.Property1;
var y = instance.Property2;
}

还是这个?

if (instance != null)
{
var x = instance.Property1;
}

if (instance != null)
{
var y = instance.Property2;
}

如果是前者,如果两行之间还有其他代码,会有什么不同吗?换句话说,编译器/优化器有多聪明?

最佳答案

编译器似乎对此一无所知。

代码:

var x = instance?.Property1;
var y = instance?.Property2;

...编译为未优化为:

IL_0000:  nop         
IL_0001: newobj UserQuery+Class..ctor
IL_0006: stloc.0 // instance
IL_0007: ldloc.0 // instance
IL_0008: brtrue.s IL_000D
IL_000A: ldnull
IL_000B: br.s IL_0013
IL_000D: ldloc.0 // instance
IL_000E: ldfld UserQuery+Class.Property1
IL_0013: stloc.1 // x
IL_0014: ldloc.0 // instance
IL_0015: brtrue.s IL_001A
IL_0017: ldnull
IL_0018: br.s IL_0020
IL_001A: ldloc.0 // instance
IL_001B: ldfld UserQuery+Class.Property2
IL_0020: stloc.2 // y
IL_0021: ret

Class..ctor:
IL_0000: ldarg.0
IL_0001: call System.Object..ctor
IL_0006: nop
IL_0007: ret

...并优化为:

IL_0000:  newobj      UserQuery+Class..ctor
IL_0005: dup
IL_0006: dup
IL_0007: brtrue.s IL_000C
IL_0009: pop
IL_000A: br.s IL_0012
IL_000C: ldfld UserQuery+Class.Property1
IL_0011: pop
IL_0012: dup
IL_0013: brtrue.s IL_0017
IL_0015: pop
IL_0016: ret
IL_0017: ldfld UserQuery+Class.Property2
IL_001C: pop
IL_001D: ret

Class..ctor:
IL_0000: ldarg.0
IL_0001: call System.Object..ctor
IL_0006: ret

两个分支检查都清楚。

关于c# - Null-Conditional 运算符是否在连续使用站点之间进行了优化,还是会导致重复检查?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34984476/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com