note 126687 added to function.array-merge
| From: | ChrisM at main dot php dot net | Date: | Thu, 16 Dec 2021 09:04:36 +0000 |
| Subject: | note 126687 added to function.array-merge | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-217376@lists.php.net to get a copy of this message | ||
I wished to point out that while other comments state that the spread operator should be faster than
array_merge, I have actually found the opposite to be true for normal arrays. This is the case in
both PHP 7.4 as well as PHP 8.0. The difference should be negligible for most applications, but I
wanted to point this out for accuracy.
Below is the code used to test, along with the results:
<?php
$before = microtime(true);
for ($i=0 ; $i<10000000 ; $i++) {
$array1 = ['apple','orange','banana'];
$array2 = ['carrot','lettuce','broccoli'];
$array1 = [...$array1,...$array2];
}
$after = microtime(true);
echo ($after-$before) . " sec for spread\n";
$before = microtime(true);
for ($i=0 ; $i<10000000 ; $i++) {
$array1 = ['apple','orange','banana'];
$array2 = ['carrot','lettuce','broccoli'];
$array1 = array_merge($array1,$array2);
}
$after = microtime(true);
echo ($after-$before) . " sec for array_merge\n";
?>
PHP 7.4:
1.2135608196259 sec for spread
1.1402177810669 sec for array_merge
PHP 8.0:
1.1952061653137 sec for spread
1.099925994873 sec for array_merge
----
Server IP: 45.112.84.4
Probable Submitter: 45.112.85.242 (proxied: 97.88.220.16)
----
Manual Page -- https://php.net/manual/en/function.array-merge.php
Edit -- https://main.php.net/note/edit/126687
Del: integrated -- https://main.php.net/note/delete/126687/integrated
Del: useless -- https://main.php.net/note/delete/126687/useless
Del: bad code -- https://main.php.net/note/delete/126687/bad+code
Del: spam -- https://main.php.net/note/delete/126687/spam
Del: non-english -- https://main.php.net/note/delete/126687/non-english
Del: in docs -- https://main.php.net/note/delete/126687/in+docs
Del: other reasons-- https://main.php.net/note/delete/126687
Reject -- https://main.php.net/note/reject/126687
Search -- https://main.php.net/manage/user-notes.php