Four PHP techniques to improve script performance

Time:2020-10-18

Usually, I write code using plain regular PHP functions to solve the problem. But for some of these problems, I came across alternative solutions that specifically improved performance.

In this article, I’d like to introduce some alternatives. This is useful if you are looking for possibilities to reduce execution time in production. Let’s see which PHP approach might be replaced by a more powerful one, and whether there are cost or trade-offs.

1. Delete duplicate items

You have a large array of duplicates, and you want to remove them so that they have only unique values.

routine

array_unique($array);

replace

array_keys(array_flip($array));

performance

I created an array with more than 4 million elements and 3 million duplicates. This is the best result:

method Execution time processing time
array_unique 787.31 MS
array_keys array_flip 434.03 MS

The alternative method is fast in this measurement1.8 times(44.87%)。 On average, the speed increased by about 1.5 times (30%). Trade off: this only applies to simple one-dimensional arrays becausearray_flipReplaced key with value.

2. Get random array records

You have a large array from which you want to select a random value.

routine

array_rand($array);

replace

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

performance

I created an array of five million elements. This is the best result:

method Execution time processing time
array_rand 25.99 microseconds
mt_rand 0.95 microseconds

The alternative is that the measurement is fast27.3 times(96.33%)。 On average, the speed increased by about 8 times (87%). This result is particularly surprising becausemt_randThe same is true for the implementation of the Mersenne twister random number generator, and since PHP 7.1, the internal randomization algorithm has been changed to use exactly the same algorithm.

3. Test alphanumeric characters

You have a string to test if it contains only alphanumeric characters.

routine

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

replace

ctype_alnum($string);

performance

I created an array containing more than 100k alphanumeric and non alphanumeric strings. This is the best result:

method Execution time processing time
preg_match 15.39 MS
ctype_alnum 2.06 MS

In this measurement, the alternative method is fast7.5 times(86.59%)。 On average, the speed increased by about four times (76%). You can apply the same content toctype_alpha()(check alphabetic characters) andctype_digit()(check numeric characters).

4. Replace substring

You have a string and want to replace part of it with another substring.

routine

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

replace

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

performance

I created an array of five million random strings. This is the best result:

method Execution time processing time
str_replace 676.59 MS
strtr 305.59 MS

The other way is2.2x(54.83%) in this measurement was faster. On average, the speed increased by about two times (51%).


Other performance improvements

These are some of the other points I’ve integrated into my coding conventions, and I’ve found that they can improve performance slightly, if applicable:

  • Prefer JSON to XML
  • Declare variables before the loop rather than in each iteration of the loop
  • Avoid function calls in loop headers (in each iteration
    for ($i=0; $i<count($array); $i)staycount()Call in get)
  • Reset memory consumption variable
  • PreferenceselectStatement instead of multipleifsentence
  • Prior torequire / includeinstead ofrequire_once / include_once(ensure proper opcode caching)

Last words: I know the discussion about premature optimization. I agree that performance in production depends on bottlenecks, such as database queries, which should be focused on when processing performance. But I think if there are faster alternatives, such as when regular expressions are easier to handle and maintain, why not use them?

last

We’ve seen that even with the current PHP 7.4 (which is much faster than previous versions of PHP), there are other ways to improve script performance. If you want to personally validate the data provided in this article, I created a repository with all the tests:

devmount / faster-php

Testing different ways to improve the performance of PHP scripts

I used Bart van hoekelen’s excellent tools to measure execution time.

Recommended Today

Explain module, import and export in JavaScript

Author: Tania rascia Crazy technology house Original text:https://www.taniarascia.com/j… In the era of the Internet, websites are mainly developed with HTML and CSS. If you load JavaScript into a page, it usually provides effects and interactions in the form of small fragments. Generally, all JavaScript code is written in a file and loaded into a filescriptTag. […]