How to optimize PHP code

While writing PHP code, you should keep following points in mind, to make your code run efficiently and quickly.

Most the optimization depends on the tuning of the webserver, compiling PHP with correct configuration options and cache usage. But, still, some what optimization can be achieved, if you,

1) “Loops” (for, foreach, while) are the sections which take most of the time of the program execution. Optimization of the loops should be the first thing you should do. Nested loops (loop inside loop) call for more attention. Take the non-variables (for which value does not change) outside the loop. eg,

for($i=0; $i<count($array); $i++)  //not good

If the array length (max iterations for the loop) is not changing, calculated it outside loop body or in the initialization portion (before first semicolon). It does not get calculated in every iteration and hence reduces load.

$length = count($array);
for($i=0; $i<$length; $i++) //good

or

for($i=0, $length=count($array); $i<$length; $i++) //good (it is same as above)

2) When using arrays or MySQL result objects use “while” or “foreach” loop. This would save us extra step of incrementing/decrementing the counter in every iteration, eg,

while ($row = mysql_fetch_assoc($result)) {
    echo $row["userid"];
}
mysql_free_result($result);  // release the memory

3) Try to avoid regular expression engine overhead wherever possible.

To search a substring, PHP function strpos() is fastest, then preg_match() and then ereg().

In the same way, PHP function str_replace() is faster than preg_replace(), which is faster than ereg_replace().

4) Use “switch” in case of multiple “if”s and “else”s. Keep most frequently occuring cases on top in the switch body. If some common cases are still there in the default section, explicitly define them at the top to prevent condition checks of multiple cases. If case condition matches at the top itself, execution comes out immediately, hence program runs faster.

5) Release memory by unsetting variables (PHP function unset(); ) which are no more used. Do it especially for resources and large arrays. For releasing MySQL resources use mysql_free_result(), close the DB connection as soon as you are done with it.

6) Use multiple parameters of echo instead of string concatenation and then echoing it, eg,

echo $var1.$var2.$var3;  //not good
echo $var1, $var2, $var3;  //good

7) Use single quote instead of double quotes when there is no varible to be printed by echo.

echo "Hello World"; //not good
echo 'Hello World'; //good
echo 'Hello ', $username, ' welcome back';

8 ) Use PHP function isset() to check the existence of a variable, before using this variable in any condition or calculation.

if ( strcmp($_POST['id'], '12345')==0  ) //not good
//if id is not set there's no point in comparision
if (isset($_POST['id']) && ( strcmp($_POST['id'], '12345')==0 ) ) //good

9) mt_rand() is four times faster than rand().

If you need to create random numbers, with or without the range, use mt_rand() instead of rand()

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>