A post on Savant-Talk got me thinking about performance issues with PHP. I believe that the key to making your PHP apps fast and scalable starts with good design practices. Here’s a checklist of what I do to keep my PHP apps running fast.
$data = '1234567890';
for ($i = 1; $i < = strlen($data); $i++) {
...
}
This code will call strlen once for every iteration of the loop. If you call strlen once and store it's result, your code will run faster.
$foo = array(1, 2, ... n);
$out = '';
foreach ($foo as $v) {
$out .= $v;
}
$v = trim(',', $v);
Can be restated as:
$foo = array(1, 2, ... n);
$out = implode(',', $n);
foreach(). The alternative syntax for looping through an array looks like this:
while(list($k, $v) = each($array)) {
...
}
In addition to being less clear about what’s going on with the loop, list() and each() are called for each iteration.
array_keys() with foreach(). foreach() returns a copy of the array value. When dealing with arrays which have large amounts of data (e.g. objects or large arrays), use array_keys() to avoid excessive memory consumption.
foreach(array_keys($array) as $ak) {
$v =& $array[$ak];
...
}
$foo = $bar makes a copy of $bar, and stores it in $foo. PHP’s garbage collection sucks, so you end up with copies of stuff all over the place, wasting memory and CPU cycles. Use a reference instead: $foo =& $bar. This makes $foo point to $bar, instead of making a copy.str_replace() and strstr(). Don’t use regexes unless you realy need them. The string functions are much faster.preg_match(), preg_replace() etc) instead of the POSIX regex functions.sprintf(). Unless you need the formatting capabilities of sprintf(), avoid it. Plain string concatenation is around twice as fast.echo instead of print(). echo is a statement (like include, if etc), so you avoid the function overhead of print().
Discussion