which is faster nested if or &&

 

I prefer to put to use && to combine logical tests in a single if statement and in other programming languages this is usually the faster method because usually if the first part of the if fails, the second part won't even be executed, thus saving time. Unfortunately after doing some times I found that is not the case for mql4. Of course using nested ifs would prevent the following test(s) if the first is false however nesting ifs requires more CPU cycles (and is therefore "slower") than a single if. So is it a wash? I'm guessing that it depends which one is faster based on how many logical tests are prevented by using a nested if.


if ( x>0 && y>0) // both are tested regardless if x<=0

do_stuff();


or


if (x>0)

if(y>0)

do_stuff();


 

Your particular example will not make much of a noticeable difference, since it is only testing variables which is quick.


But if you have something like:


if (somegreatbigheavyfunction()>0 && evenbiggerfunction()>0)...


Then you will notice the difference using the nested-if.

 
bunnychopper:

I prefer to put to use && to combine logical tests in a single if statement and in other programming languages this is usually the faster method because usually if the first part of the if fails, the second part won't even be executed, thus saving time. Unfortunately after doing some times I found that is not the case for mql4. Of course using nested ifs would prevent the following test(s) if the first is false however nesting ifs requires more CPU cycles (and is therefore "slower") than a single if. So is it a wash? I'm guessing that it depends which one is faster based on how many logical tests are prevented by using a nested if.


if ( x>0 && y>0) // both are tested regardless if x<=0

do_stuff();


or


if (x>0)

if(y>0)

do_stuff();



the second option is faster