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.
| Function | Alternative |
|---|---|
| array_diff | Try using array_diff_key, as keys are unique |
| array_intersect | Try using array_intersect_key, as keys are unique |
| array_udiff | Try using array_diff_key, as keys are unique |
| array_uintersect | Try using array_intersect_key, as keys are unique |
| array_unique | Use array_count_values and array_keys |
| uasort | Build the array to use non-u sort |
| uksort | Build the array to use non-u sort |
| usort | Build the array to use non-u sort |
| in_array | Build the array to be able to replace it with isset() |
| preg_replace | Replace with str_replace(), for simple replacements |
| array_search | Replace with array_key_exists() |
| array_shift | Process the array the other way with array_pop() |
| array_unshift | Process the array the other way with array_push() |
| strstr | Use 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_resource | Use === 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.