Replace nested if expression with AND

I am wondering if nested is better than the AND operator. I have a loop that goes on so many times, so I am thinking of faster execution. Below is a code that has the same logic with my code. The nested if statement is inside the loop.

   for ( int i = 0; i < array.length; i++)
   {
      // do stuff
      if (x == 5)
      {
         if (y == 3)
         {
             // do stuff
         }
      }
   }  

Will my code be faster with a significant difference if I replace the nested one, if with this and the STATEMENT?

     if ((x == 5) && (y == 3))
           // do stuff

I read this link, but I did not find the answer. I am a student and still studied, thanks for all the feedback!

+5
source share
4 answers

.NET will stop checking if the first part of the conditional value is false, so there will be no difference between them.

+3
source

, , .

IL / ( LINQPad):

IL_0000:  ldc.i4.5    
IL_0001:  stloc.0     
IL_0002:  ldc.i4.s    0A 
IL_0004:  stloc.1     
IL_0005:  ldloc.0     
IL_0006:  ldc.i4.5    
IL_0007:  bne.un.s    IL_000D
IL_0009:  ldloc.1     
IL_000A:  ldc.i4.3    
IL_000B:  pop         

:

:

IL_0001:  ldc.i4.5    
IL_0002:  stloc.0     
IL_0003:  ldc.i4.s    0A 
IL_0005:  stloc.1     
IL_0006:  ldloc.0     
IL_0007:  ldc.i4.5    
IL_0008:  ceq         
IL_000A:  ldc.i4.0    
IL_000B:  ceq         
IL_000D:  stloc.2     
IL_000E:  ldloc.2     
IL_000F:  brtrue.s    IL_0020
IL_0011:  nop         
IL_0012:  ldloc.1     
IL_0013:  ldc.i4.3    
IL_0014:  ceq         
IL_0016:  ldc.i4.0    
IL_0017:  ceq         
IL_0019:  stloc.2     
IL_001A:  ldloc.2     
IL_001B:  brtrue.s    IL_001F
IL_001D:  nop         
IL_001E:  nop 

:

IL_0001:  ldc.i4.5    
IL_0002:  stloc.0     
IL_0003:  ldc.i4.s    0A 
IL_0005:  stloc.1     
IL_0006:  ldloc.0     
IL_0007:  ldc.i4.5    
IL_0008:  bne.un.s    IL_0013
IL_000A:  ldloc.1     
IL_000B:  ldc.i4.3    
IL_000C:  ceq         
IL_000E:  ldc.i4.0    
IL_000F:  ceq         
IL_0011:  br.s        IL_0014
IL_0013:  ldc.i4.1    
IL_0014:  nop         
IL_0015:  stloc.2     
IL_0016:  ldloc.2     
IL_0017:  brtrue.s    IL_001B
IL_0019:  nop 
+9

, . , ( )

, if , :

String s=//...
if(s==null)return;
if(s.Length > 0) //do something

AND :

if ((s!=null) && (s.Length > 0)) //Dosomething

:

if ((s.Length > 0) && (s!=null) ) //Dosomething

, if s

+3

In the compiled code, there are no reasons why the speeds should be different, they will translate exactly into the same assembly code. I definitely agree with the readability factor, and it will also shorten the length of your class.

+1
source

All Articles