Monday, July 13, 2009

Speeding up conditional (IF/ELSE) statements

Do you know that conditional statements can be actually sped up if you use the appropriate statements and expressions?

Take a look at the following 2 codes:

<?php
if($test==5){
print 't';
}else{
print 't2';
}
?>


and

<?php
($test == 5) ? print 't' : print 't2';
// reason that i am using print is
// because echo cannot be used.
?>


The second code block is actually faster than the first. I looped both codes 10 times and I got the following results: 4.31537628174E-5s for IF/ELSE (first code) and 1.50203704834E-5s for (second code) respectively. A difference of 2.8133392334E-5 seconds.

However, the shortcoming of the second code block is that you can only put in one function in the condition at one time.

Meaning to say you cannot do this:
<?php
($test == 5) ? print 't';$i++ : print 't2';
?>

This will give a syntax error on PHP.

2 comments:

gamers2000 said...

Case switch?

thephpdeveloper said...

you can't really do that for case
unless you have nested

e.g.

($var ? call() : ($var2 ? call2() : call3()));