[PHP Performance] Comparison between array_merge and + union

I wrote a code in PHP to compare the performance between array_merge and the + union :

I chose an array with 2 elements, and it will merge 5000 times.

PHP code :


<?php

// Variables
$limit = 5000;
$arr_size = 2;

// Build a base array
for ($i=0;$i<$arr_size;$i++) {
 $arr[$i] = 0;
}

// Test 1 with array_merge
$tab1 = array();
$j = 0;
$temp = microtime(true);
while ($j<$limit) {
 $tab1 = array_merge($tab1, $arr);
 $j++;
}
$temp1 = (microtime(true) - $temp);
echo "\n Temp with array_merge : ".$temp1;

// Test 2 with + union
$tab2 = array();
$k = 0;
$temp = microtime(true);
while ($k<$limit) {
 $tab2 += $arr;
 $k++;
}
$temp2 = (microtime(true) - $temp);

echo "\n Temp with + union : ".$temp2."\n";

// Compare the time used by the 2 ways
echo sprintf('Union est %5d fois plus rapide que array_merge', ((float)$temp1/(float)$temp2));

You can find the code in github : https://gist.github.com/cupidcb/9551486

Advertisements

2 comments on “[PHP Performance] Comparison between array_merge and + union

    • We have thousands of ways to see the results. I let u discover by yourself.
      Tips : you have to find how to execute PHP 😉 Let me know if it could help u.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s