Oct 28 2010

Lazy: Change the way you code and speed up php.

Echo vs Print – With current versions of PHP Echo is the way to go. When you have to print multiple strings, Echo allows you to skip the overhead of concatenation when you use “,” instead of “.” between strings.

Single vs Double quote – when possible use single quote, as double quote strings are processed by PHP.

Accessing data in Arrays – When working with an associative array, PHP operates quickest when the variable array is enclosed in single quotes such as $row[‘thomas’].

Function vs no functions – Everything is passed by reference after PHP 5, which significantly speeds things up, however they are still less efficient than code without functions. If you reuse the code multiple times within the document, functions are a must. If you are only using it once, it is just extra overhead. (This statement is against everything taught in school.)

Extra variables – Try to use as few variables as possible. For example:
$a=time();
$tomorrow=$a + (24*60*60);
is less efficient than
$tomorrow=$time+(24*60*60);

Count () in for loop – There are exceptions to the ‘use as few variables as possible’ rule. The most common is when you have the count function in a conditional loop.

Unset – when you are done using a variable, you can regain the memory by using unset.

Close connections /file handers – Give PHP back the resources when they are not needed.

Cache page if possible.

Lazy way to test

$time = microtime(true);
#
# code to be benchmarked here
#
echo '

Time elapsed: ',microtime(true) - $time, ' seconds';