Thomas Flinkow
Thomas Flinkow

Reputation: 5115

Empty if-block not optimized away?

Will the following empty if-block be optimized away?

public class C 
{
    private bool foo = false;
    
    public void M() 
    {
        if(foo) {}
    }
}

SharpLab (master 5 Dec 2020, Release) indicates that the compiler does not optimize the if-block away:

.method public hidebysig instance void M () cil managed 
{
    .maxstack 8

    IL_0000: ldarg.0
    IL_0001: ldfld bool C::foo
    IL_0006: pop
    IL_0007: ret
}

Should the compiler not be able to see that ldfld followed by pop has no effect and the three instructions (ldarg.0 too) do not need to be emitted?

I cannot think of possible side effects that would occur when not emitting ldfld (as there could be when calling a method inside the if-block).


Further, the JIT ASM that SharpLab generates also does not seem to optimize the empty if-block away:

C.M()
    L0000: movzx eax, byte ptr [ecx+4]
    L0004: ret

Am I right in thinking that the JIT will still optimize the empty if-block away?

Thank you in advance!

Upvotes: 0

Views: 142

Answers (1)

user555045
user555045

Reputation: 64904

Further, the JIT ASM that SharpLab generates also does not seem to optimize the empty if-block away:

C.M()
    L0000: movzx eax, byte ptr [ecx+4]
    L0004: ret

The actual if block has been optimized away, if it existed it would have looked comparable to this:

C.M()
    L0000: movzx eax, byte ptr [ecx+4]
    L0004: test eax, eax
    L0006: je short L0008
    L0008: ret

But that did not happen, the JIT-compiler apparently figured out that this would not be useful.

Only the load of the boolean field still exists.

Upvotes: 2

Related Questions