4 PHP Tricks to Boost Script Performance

Normally I write code by using the conventional, obvious PHP functions to solve corresponding problems. But for some of these problems I came across alternative solutions that especially increase performance.

1. Removing duplicates

🐌 Conventional

array_unique($array);

⚡ Alternative

array_keys(array_flip($array));

⏲ Performance

2. Get random array element

🐌 Conventional

array_rand($array);

⚡ Alternative

$array[mt_rand(0, count($array) - 1)];

⏲ Performance

3. Test for alphanumeric characters

🐌 Conventional

preg_match('/[a-zA-Z0-9]+/', $string);

⚡ Alternative

ctype_alnum($string);

⏲ Performance

4. Replace substrings

🐌 Conventional

str_replace('a', 'b', $string);

⚡ Alternative

strtr($string, 'a', 'b');

⏲ Performance

Additional performance improvements

  • Prefer JSON over XML
  • Declare variables before, not in every iteration of the loop
  • Avoid function calls in the loop header (in for ($i=0; $i<count($array); $i) the count() gets called in every iteration)
  • Unset memory consuming variables
  • Prefer switch statement over multiple if statements
  • Prefer require/include over require_once/include_once (ensure proper opcode caching)

Wrap it up

--

--

creator. developer. consultant.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store