C# performance comparison: AND operator vs if cascade
Ok, this post will be a way to win macro seconds in your program and you probably don’t care about these macro seconds. But, if you work on a real time server, each macro second could be important.
The purpose in this post is: what is the better between “&& comparator” and “if cascade” ?
- int i = 5;
- if (i > 0 && i < 10)
- i = -1;
or
- int i = 5;
- if (i > 0)
- {
- if (i<10)
- i = -1;
- }
as often, the answer is in the intermediate language:
We could check that. For the first example:
- .method private hidebysig static void Main(string[] args) cil managed
- {
- .entrypoint
- // Code size 26 (0x1a)
- .maxstack 2
- .locals init ([0] int32 i,
- [1] bool CS$4$0000)
- IL_0000: nop
- IL_0001: ldc.i4.5
- IL_0002: stloc.0
- IL_0003: ldloc.0
- IL_0004: ldc.i4.0
- IL_0005: ble.s IL_0011
- IL_0007: ldloc.0
- IL_0008: ldc.i4.s 10
- IL_000a: clt
- IL_000c: ldc.i4.0
- IL_000d: ceq
- IL_000f: br.s IL_0012
- IL_0011: ldc.i4.1
- IL_0012: nop
- IL_0013: stloc.1
- IL_0014: ldloc.1
- IL_0015: brtrue.s IL_0019
- IL_0017: ldc.i4.m1
- IL_0018: stloc.0
- IL_0019: ret
- } // end of method Program::Main
We could see 4 testing operations (ceq, brtrue …)
in the second example:
- .method private hidebysig static void Main(string[] args) cil managed
- {
- .entrypoint
- // Code size 31 (0x1f)
- .maxstack 2
- .locals init ([0] int32 i,
- [1] bool CS$4$0000)
- IL_0000: nop
- IL_0001: ldc.i4.5
- IL_0002: stloc.0
- IL_0003: ldloc.0
- IL_0004: ldc.i4.0
- IL_0005: cgt
- IL_0007: ldc.i4.0
- IL_0008: ceq
- IL_000a: stloc.1
- IL_000b: ldloc.1
- IL_000c: brtrue.s IL_001e
- IL_000e: nop
- IL_000f: ldloc.0
- IL_0010: ldc.i4.s 10
- IL_0012: clt
- IL_0014: ldc.i4.0
- IL_0015: ceq
- IL_0017: stloc.1
- IL_0018: ldloc.1
- IL_0019: brtrue.s IL_001d
- IL_001b: ldc.i4.m1
- IL_001c: stloc.0
- IL_001d: nop
- IL_001e: ret
- } // end of method Program::Main
We could see 6 testing operations (ceq, brtrue …)
In fact, we could win 20% execution time with operator &&.
The simpler the better !!!