[php-src] Issue #8283: Performance: array_reduce is drastically slower (~1000x) than implementing the same logic with foreach

From: Date: Thu, 31 Mar 2022 06:23:09 +0000
Subject: [php-src] Issue #8283: Performance: array_reduce is drastically slower (~1000x) than implementing the same logic with foreach
Groups: php.bugs 
Request: Send a blank email to php-bugs+get-240592@lists.php.net to get a copy of this message
Issue: https://github.com/php/php-src/issues/8283
Comment Author: drealecs

Given that the culprit was identified as the trigger for array copy on write operation, a common
solution in this kind of cases would be to make sure we deal with a mutable resource reference
instead of a plain array.

You will have good performance if you change the $initial parameter from
[] to new ArrayObject():
```php
$result = array_reduce($data, function ($carry, $item) {
    @$carry[$item]++;
    return $carry;
}, new ArrayObject())
    ->getArrayCopy();
```


Thread (1 message)

  • drealecs
« previous php.bugs (#240592) next »