Was playing with the JIT ASM code and found this interesting difference when using the Negation operator as compared to the if and else block.
public class C
{
public bool NegationOperator(bool input)
{
return !input;
}
public bool IfElseCondition(bool input)
{
if (input)
{
return false;
}
else
{
return true;
}
}
}
As you can see above we are doing the same thing, in both of the code-block we are just reverting the result based on the input value.
I expect to have the same code-gen generated for both of the code blocks because we are dealing with all constants values except input parameters (which is technically also a constant as it can have possible 2 values only) so JIT can see that and should fold.
But interestingly if-else block code generates a different code than the NegationOperator method.
C.NegationOperator(Boolean)
L0000: xor eax, eax
L0002: test dl, dl
L0004: sete al
L0007: ret
C.IfElseCondition(Boolean)
L0000: test dl, dl
L0002: je short L0007
L0004: xor eax, eax
L0006: ret
L0007: mov eax, 1
L000c: ret
Sharplab link
Why there is a difference in codegen!? Can't we generate the same ASM code for the IfElseCondition method just like we did it for NegationOperator method? I guess we can avoid je instruction in IfElseCondition.
Was playing with the JIT ASM code and found this interesting difference when using the Negation operator as compared to the
ifandelseblock.As you can see above we are doing the same thing, in both of the code-block we are just reverting the result based on the input value.
I expect to have the same code-gen generated for both of the code blocks because we are dealing with all constants values except
inputparameters (which is technically also a constant as it can have possible 2 values only) so JIT can see that and should fold.But interestingly
if-elseblock code generates a different code than theNegationOperatormethod.Sharplab link
Why there is a difference in codegen!? Can't we generate the same ASM code for the
IfElseConditionmethod just like we did it forNegationOperatormethod? I guess we can avoidjeinstruction inIfElseCondition.