다음을 통해 공유


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” ?

 

  1. int i = 5;  
  2. if (i > 0 && i < 10)  
  3.      i = -1;  

or

  1. int i = 5; 
  2. if (i > 0) 
  3. {  
  4.      if (i<10)  
  5.           i = -1;  
  6. }  

as often, the answer is in the intermediate language:

We could check that. For the first example:

 

  1. .method private hidebysig static void Main(string[] args) cil managed  
  2.   
  3. {  
  4. .entrypoint  
  5. // Code size 26 (0x1a)  
  6. .maxstack 2  
  7. .locals init ([0] int32 i,  
  8. [1] bool CS$4$0000)  
  9. IL_0000: nop  
  10. IL_0001: ldc.i4.5  
  11. IL_0002: stloc.0  
  12. IL_0003: ldloc.0  
  13. IL_0004: ldc.i4.0  
  14. IL_0005: ble.s IL_0011  
  15. IL_0007: ldloc.0  
  16. IL_0008: ldc.i4.s 10  
  17. IL_000a: clt  
  18. IL_000c: ldc.i4.0  
  19. IL_000d: ceq  
  20. IL_000f: br.s IL_0012  
  21. IL_0011: ldc.i4.1  
  22. IL_0012: nop  
  23. IL_0013: stloc.1  
  24. IL_0014: ldloc.1  
  25. IL_0015: brtrue.s IL_0019  
  26. IL_0017: ldc.i4.m1  
  27. IL_0018: stloc.0  
  28. IL_0019: ret  
  29. } // end of method Program::Main  

 

We could see 4 testing operations (ceq, brtrue …)

in the second example:

  1. .method private hidebysig static void Main(string[] args) cil managed  
  2. {  
  3. .entrypoint  
  4. // Code size 31 (0x1f)  
  5. .maxstack 2  
  6. .locals init ([0] int32 i,  
  7. [1] bool CS$4$0000)  
  8. IL_0000: nop  
  9. IL_0001: ldc.i4.5  
  10. IL_0002: stloc.0  
  11. IL_0003: ldloc.0  
  12. IL_0004: ldc.i4.0  
  13. IL_0005: cgt  
  14. IL_0007: ldc.i4.0  
  15. IL_0008: ceq  
  16. IL_000a: stloc.1  
  17. IL_000b: ldloc.1  
  18. IL_000c: brtrue.s IL_001e  
  19. IL_000e: nop  
  20. IL_000f: ldloc.0  
  21. IL_0010: ldc.i4.s 10  
  22. IL_0012: clt  
  23. IL_0014: ldc.i4.0  
  24. IL_0015: ceq  
  25. IL_0017: stloc.1  
  26. IL_0018: ldloc.1  
  27. IL_0019: brtrue.s IL_001d  
  28. IL_001b: ldc.i4.m1  
  29. IL_001c: stloc.0  
  30. IL_001d: nop  
  31. IL_001e: ret  
  32. } // 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 !!!