[php-src] Issue #8283: Performance: array_reduce is drastically slower (~1000x) than implementing the same logic with foreach
| From: | kamil-tekiela | Date: | Wed, 30 Mar 2022 21:56:44 +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-240584@lists.php.net to get a copy of this message | ||
Issue: https://github.com/php/php-src/issues/8283
Comment Author: kamil-tekiela
I don't think big O notation applies here.
FWIW, your examples are not comparable, because the one with foreach doesn't use function calls
or array reassignment. If you create the same example, the performance is identical.
See these two examples:
```
<?php
declare(strict_types=1);
// generate a large sample of pseudo-random data which may have duplicates
$data = [];
for ($i = 0; $i < 40000; $i++) {
$data[] = crc32((string) $i);
}
echo 'Foreach';
function reduce($carry, $item)
{
@$carry[$item]++;
return $carry;
}
$start = hrtime(true);
$result = [];
foreach ($data as $item) {
$result = reduce($result, $item);
}
$durationNs = hrtime(true) - $start;
echo sprintf('%f s', $durationNs / 1_000_000_000);
echo "\n\n";
unset($start, $result, $item, $durationNs);
echo 'Array reduce';
$start = hrtime(true);
$result = array_reduce($data, function ($carry, $item) {
@$carry[$item]++;
return $carry;
}, []);
$durationNs = hrtime(true) - $start;
echo sprintf('%f s', $durationNs / 1_000_000_000);
```
array_reduce isn't the culprit. It's the function calls and constant
reassignment of arrays; the latter being the biggest offender.
So, I am not sure what exactly you consider to be a bug. In terms of performance
array_reduce is almost identical to naive foreach loop if implemented
exactly the same way. If you compare apples to oranges, then obviously, you will notice a
difference.