note 126393 added to function.array-merge
| From: | MartinK at main dot php dot net | Date: | Mon, 06 Sep 2021 12:58:00 +0000 |
| Subject: | note 126393 added to function.array-merge | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-216870@lists.php.net to get a copy of this message | ||
Another commentator suggest that a "foreach loop is faster than array_merge to append values to
an existing array", and goes on to prove this by timing some code.
It starts with a preamble that sets up $chars as an array with 15000 elements, each in turn being an
array with 10 elements, and then testing the timing of this code:
<?php
$new = [];
foreach ($chars as $splitArray) {
$new = array_merge($new, $splitArray);
}
?>
It then times this functionally equivalent code:
<?php
$new = [];
foreach ($chars as $splitArray) {
foreach ($splitArray as $value) {
$new[] = $value;
}
}
?>
and concludes that array_merge is 1400 times slower than a foreach loop.
Of course, the problem isn't that array_merge is slow, the problem is that it's being
called 15000 times, meaning that it copies 1125075000 array elements, instead of just 150000. (That
is, it's making 7500 times as many copies.)
More appropriate would be this _also_ functionally equivalent code:
<?php
$new = array_merge(...$chars);
?>
which turns out to be roughly 25% faster than that foreach loop.
Of course, if you can modify an existing array, then that will usually be faster than copying the
entire existing array plus a few new elements.
In that case I would write:
<?php
push_array($new, ...$chars);
?>
... which again beats the naive foreach loop by about 25%.
Even without the speed improvement, the elegance of a single line of code instead of six is hard to
beat.
----
Server IP: 45.112.84.4
Probable Submitter: 45.112.85.242 (proxied: 58.84.89.180)
----
Manual Page -- https://php.net/manual/en/function.array-merge.php
Edit -- https://main.php.net/note/edit/126393
Del: integrated -- https://main.php.net/note/delete/126393/integrated
Del: useless -- https://main.php.net/note/delete/126393/useless
Del: bad code -- https://main.php.net/note/delete/126393/bad+code
Del: spam -- https://main.php.net/note/delete/126393/spam
Del: non-english -- https://main.php.net/note/delete/126393/non-english
Del: in docs -- https://main.php.net/note/delete/126393/in+docs
Del: other reasons-- https://main.php.net/note/delete/126393
Reject -- https://main.php.net/note/reject/126393
Search -- https://main.php.net/manage/user-notes.php