Faster Array Merging in PHP

I recently read a tweet (that I'm unable to find) stating that adding two arrays together is faster than using array_merge, so I decided to test it.

I wrote a quick file that contains 3 for loops, each doing 10.000.000 iterations. Below are the benchmarks.

Benchmarks

Below is the output of my benchmarking script.

Testing with ['one' => 1, 'two' => 2, 'three' => 3] and ['two' => 10, 'three' => 3, 'four' => 4]

Will loop over each command 10.000.000 times.

testing array_merge...
Output: {"one":1,"two":10,"three":3,"four":4}
7.45864s

testing [] + []...
Output: {"two":10,"three":3,"four":4,"one":1}
0.94747s

testing [] += []...
Output: {"two":10,"three":3,"four":4,"one":1}
0.86479s

As you can see above, ten million merges using [] + [] barely took a second to complete, while array_merge ran for almost 7.5 seconds.

In the last test ([] += []) I simply appended to an array that I setup outside the for loop, because creating a new array each time almost doubled the runtime.

Differences

To get similar results as array_merge you should specify the arrays in a reverse order. Example:

array_merge($array1, $array2)
$array2 += $array1

This is because in array_merge, the later arrays will have a higher priority, but with adding arrays together, the first has the highest priority.

Another thing you might have noticed is that the output is not identical. In array_merge it kept the same order, but for the others, it is reversed (two, three, four, one). This happens because I reversed the order, as stated above. The actual content, however, is identical.

Show Comments