Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple if blocks or a single if with AND condition

If I need to check multiple conditions, which is the preferred way with respect to performance

if( CND1 && CND2 && CND3 && CND4)
{
}
else
{
}

or

  if(CND1)
{
   if(CND2)
   {
      if(CND3)
      {
         if(CND4)
         {
         }
         else
         {
         }
      }
      else
      {
      }
   }  
else
   {
   }
}
    }
like image 659
Ram Avatar asked Dec 23 '22 03:12

Ram


1 Answers

The performance is the same since it will stop checking the arguments once it has found a false one (short-circuiting), so definitely go with the first one. It's one line compared to like, 10. It also means that your else will be much easier to handle.

like image 60
nickf Avatar answered Jan 13 '23 03:01

nickf