Hi!

Using array_merge() inside a loop can greatly impact performance. From the
tests I did, doing it in the middle costs 250% more than doing it later:

- Inside: for(...) $x = array_merge($x, $y)
- After: for(...) $x[] = $y; array_merge(... $x)

Even using array_push() doesn't seem like a good alternative as it costs
140%.

https://pastebin.com/s7f4Ttm3
https://3v4l.org/Vqt7o (+83% for array_push(), +760% for array_merge()
inside)

As far as I know, the array_merge() function makes a copy of the array,
rather than updating the input array. It makes sense, but in some
situations, not so rare, it might be possible to optimize when the
destination variable is part of the argument.

$arr = array_merge($arr, [ 1, 2, 3 ]); // or
$arr = array_merge([ 1, 2, 3 ], $arr);

This could reduce processing cost and memory consumption, as it would no
longer be necessary to copy the array to generate another one.

Anyway, I don't know if this is actually possible, or if the cost-benefit
would be better than what there is today. But I believe it is a path to be
thought of.


Atenciosamente,
David Rodrigues

Reply via email to