PHP Performance tips

I have programmed PHP for a long time, and there are many tutorials on the web that is learning about double/single quotes, for loops and so on. In my scenario i think its much more important to learn about when to use array, how to use it, how to initialize big arrays, and so on. In this tutorial, we will take a look at how we can increase performance of php scripts in general.

Initialize when needed

There are so many projects where you see big arrays, including files unnecessary and more on the internet. In this section we can elaborate on this fact, and learn how to reduce memory usage of your php application by a lot.

Do you really need to initialize that big array?

Huge CMS systems with tons of database calls and big configration files allways have a issue with this. This is just how it is, that's why a CMS doesn't allways scale.

Say you have a site, with many parts and functionality depending on the URI. You may see this in some php scripts:

<?php $colors = array( /* 5000 colors */);
$cars = array( /* 4000 cars */);

if ($_GET['s'] = 'index'){
 // Output a list of colors
}elseif($_GET['s'] == 'cars'){
 // Output a list of cars.
} // etc.
??>

So in this example we did 2 mistakes, we initialized $colors and $cars when we didn't need to do it, the correct will be to initialize $colors array in the if-case equals 'index'.

This is much better:

<?php if ($_GET['s'] = 'index'){
 $colors = array( /* 5000 colors */);
 // Output a list of colors
}elseif($_GET['s'] == 'cars'){
 $cars = array( /* 4000 cars */);
 // Output a list of cars.
} // etc.
??>

Do notice that pagination would be perfect if it was a database that held the colors/cars, since we can then reduce 5000 cars at once to 10 per page.

Use autoloader

Autoloaders is nice, if we structure our files nicely with nice file convention (eg. Test.php holds the Test class) we can create a very simple autoloader to include the file when we need it!

Initialize variables before working with them

Try to initialize all your variables before working with them, this gives you cleaner code and more control aswell as performance boosts.

<?php // Correct
 $var = null;
 if (expression)$var = 'car';
 if ($var == 'car'){

 }
 // Wrong
 if (expression)$var = 'car';
 if ($var == 'car'){

 }
??>

Please write the code you see on this image:

Human verification