I'm just trying to get into IL because I'm working with code-injection. I'm required to analyze code and cover various cases.
Sadly it doesn't work to inject a method call at the end if the last instructions are inside an if-clause, because the call is being contained by the paranthesis then.
Now I've been analyzing if-code being translated into IL and I'm a bit confused by how this is done. Obviously the compiler reverses the if. Is this because of performance reasons? If so by how far does this improve performance?
See for yourself:
string test;
Random rnd = new Random();
bool b = rnd.Next(0, 10) == 3;
if (b)
{
// TRUE
test = "True branch";
// END TRUE
}
else
{
// FALSE
test = "False branch";
//END FALSE
}
and this is the output:
IL_0000: nop
IL_0001: newobj instance void [mscorlib]System.Random::.ctor()
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: ldc.i4.0
IL_0009: ldc.i4.s 10
IL_000b: callvirt instance int32 [mscorlib]System.Random::Next(int32, int32)
IL_0010: ldc.i4.3
IL_0011: ceq
IL_0013: stloc.2
IL_0014: ldloc.2
IL_0015: ldc.i4.0
IL_0016: ceq
IL_0018: stloc.3
IL_0019: ldloc.3
IL_001a: brtrue.s IL_0026
IL_001c: nop
IL_001d: ldstr "True branch"
IL_0022: stloc.0
IL_0023: nop
IL_0024: br.s IL_002e
IL_0026: nop
IL_0027: ldstr "False branch"
IL_002c: stloc.0
IL_002d: nop
IL_002e: ret
As you can see, after the comparison of the Random result with the const 3 it does a comparision against 0 again and thus reverses the result which is equivalent to if (false)
.
What reason has this? Isn't it less performant since you need additional instructions? Does this happen always?