PHP Optimization Tips

As most languages PHP allows many ways to solve a problem. Some are faster then others. Here are a few ways to improve your PHP code.

Loop

At some point your program will require a loop. And loop is considered as efficiency killer if you have many nested loop (means loop in a loop) as one loop will required to run ‘n’ times and if you have 1 nested loop, this means your program will have to run n2 times. There are many ways we can define a loop in PHP. But how do you know which one is the best way to loop your data? Apparently, using a for loop is better than foreach and while loop if the maximum loop is pre-calculated outside the for loop!

// For each loop the count function is being called.
for($i =0; $i < count($array);$i++){
echo 'This is bad';
}
 
#Better than foreach and while loop
$total = (int)count($array);
for($i =0; $i < $total;$i++){
echo 'This better, max loop was pre-calculated';
}

Single Vs Double Quotes

single(’) quote is faster than double(”) quote. Why? Because PHP will scan through double quote strings for any PHP variables (additional operation). So unless you have a $var inside the string use single quotes.

$var = 'I have some text';
$var2 = "I have some text"; // We dont have vars so single would be good;
$var3 = "I have some $var"; // In this case the double quotes is necessary

Pre increment vs Post increment

In PHP, it seems like pre increment is better than the other ways of performing an increment. Its around 10% better than post increment? The reason? Some said that post increment made certain copy unlike pre increment.

$i++;
$++i
$i+=1;
$i = $i + 1;

Echo Vs Print

echo is better. But how much better? Its around 12%-20% faster using echo compare to print when there is no $ symbol in the printing string. And around 40-80% faster if there is an $ symbol used in a printing string!

Dot Vs Commas Concatenation

I use dot to concatenate my stuff. Such as the one shown below:

$a = 'PHP  ';
$b = 'Tips';
 
echo $a.$b;

The other way is:

$a = 'PHP ';
$b = 'Tips';
echo $a,$b;

Tests show that dot is more preferable if there are no variables or $ symbol involved which is around 200% faster. On the other hand, commas will help to increase around 20%-35% efficiency when dealing with $ symbols.

explode Vs preg_split

To split a string the usual way is to use explode because it support even on PHP4.0 and that’s also what i was taught on school. The answer in term of efficiency is explode. Split supports regular express and this makes it quite the same comparison between str_replace and preg_replace, anything that have regular expression support will usually be a bit more slower than those that doesn’t support it. It took around 20.563% faster using explode in PHP.

These benchmarks and others can be found here: http://net-beta.net/ubench/

2 Comments

  1. Pingback: uberVU - social comments

  2. Pingback: Tips PHP Optimization | Openguider

Leave a Reply