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:

print 't';
print 't2';


($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:
($test == 5) ? print 't';$i++ : print 't2';

This will give a syntax error on PHP.


gamers2000 said...

Case switch?

thephpdeveloper said...

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


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