PHP Benchmark: The array plus operator VS array_merge

Posted: August 13th, 2011 | Author: | Filed under: PHP | Tags: , , , | No Comments »

Just a quick post about a benchmark that quite surprised me. The array plus operator ($arr1 + $arr2) is over 6 times faster compared to array_merge. I did expect that to be faster, but not that much. This is the benchmark I used:

nadav@shesek:~$ time php -r '$x=array("x"=>1, "y"=>2); $y = array("y"=>3, "z"=>4);
> for ($i=1; $i<=500000; $i++) { $y + $x; }'

real	0m1.437s
user	0m1.392s
sys	0m0.024s

nadav@shesek:~$ time php -r '$x=array("x"=>1, "y"=>2); $y = array("y"=>3, "z"=>4);
> for ($i=1; $i<=500000; $i++) { array_merge($x, $y); }'

real	0m9.994s
user	0m7.472s
sys	0m2.400s

The results were about the same for several executions.

A couple of things should be be noted about the array plus operator:

  1. As opposed to array_merge, it overwrites numeric keys too. If you need to merge the values of two arrays with numeric keys, use array_merge instead
  2. If you need recursive merge, use array_merge_recursive instead.
  3. The values from the first array overwrites the values from the second, as opposed to array_merge. So the equivalent of array_merge($a, $b) is $b + $a, not $a + $b.
  4. Example:

    $arr = array('a' => 1, 'b' => 2, 'c' => 3);
    $arr = array('b' => 4) + $arr;
    // $arr is now array('a' => 1, 'b' => 4, 'c' => 3)