c# - Is the Null-Conditional operator optimized across consecutive usages sites or does it result in duplicate checks? -
does using null-conditional operator duplicate null checks? example
var x = instance?.property1; var y = instance?.property2;
does compiled this:
if (instance != null) { var x = instance.property1; var y = instance.property2; }
or this?
if (instance != null) { var x = instance.property1; } if (instance != null) { var y = instance.property2; }
if former, make difference if there other code in between both lines? in other words, how smart compiler/optimizer?
the compiler appears quite ignorant of this.
the code:
var x = instance?.property1; var y = instance?.property2;
...compiles non-optimized to:
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
...and optimized as:
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
both 2 branch checks.
Comments
Post a Comment