note 126393 deleted from function.array-merge by salathe

From: Date: Mon, 06 Sep 2021 22:42:34 +0000
Subject: note 126393 deleted from function.array-merge by salathe
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-216873@lists.php.net to get a copy of this message
Note Submitter: Martin K ---- [Editor's Note: the 1125075000 elements are not copied (CoW); the performance is bad due to function call overhead.] 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.

« previous php.notes (#216873) next »