Avoid Those Slow Functions

July 9, 2015 · View on GitHub

There are a few PHP native functions that should be avoided for speed reasons. They are listed below.

FunctionAlternative
array_diffTry using array_diff_key, as keys are unique
array_intersectTry using array_intersect_key, as keys are unique
array_udiffTry using array_diff_key, as keys are unique
array_uintersectTry using array_intersect_key, as keys are unique
array_uniqueUse array_count_values and array_keys
uasortBuild the array to use non-u sort
uksortBuild the array to use non-u sort
usortBuild the array to use non-u sort
in_arrayBuild the array to be able to replace it with isset()
preg_replaceReplace with str_replace(), for simple replacements
array_searchReplace with array_key_exists()
array_shiftProcess the array the other way with array_pop()
array_unshiftProcess the array the other way with array_push()
strstrUse strpos() for simple searches
uniqid()Always mention entropy (2nd parameter)
array_walk()Use foreach(source as &variable) { }
array_map()Use foreach(source as &variable) { }
range()You can use generators, for preventing building an array in memory
is_null()Use === null or similar
is_resourceUse === false or similar
is_bool()Use === false or similar
intval()Cast to (int)
floatval()Cast to (float)
strval()Cast to (string)
boolval()Cast to (bool)
settype()Cast to (bool), (string), (int) or (float)

Increment Operator

Even if it's not a function, the pre-increment operator is faster than the post-increment operator, due to a memory copy in the case of the later.

Note that replacing $i++ by ++$i is not straightforward : any situation where the result is assigned to another variable or used in an expression should be left as is, or refactored.

<?php

// Safe replacements
for($i = 0; $i < 10; $i++) { 
	//Some work here
}
$d++; // alone on its line

// Review before replacing
$a = $b++;
$c = pow($d++, 2); // raise $d to the power of 2, not $d + 1

?>

Rule Details

Using any of the functions mentioned above will trigger a warning.

<?php

// avoid using array_unique
$distinct = array_unique($incomingArray);

// use a cast
$price = floatval($source['price']);

?>

When Not To Use It

Those are micro-optimization compared to any architecture optimization that are beyond the scope of this document. Don't start a manual replacement of all occurrences with faster version, but keep this in mind when you code something new.

When you have coding conventions pushes toward using some functions rather than others, keep the convention consistent.

Further Readings