[php-src] PR #21787: [ext/standard] Specialize array_sum()/array_product() for packed long arrays
| From: | mehmetcansahin | Date: | Fri, 17 Apr 2026 14:34:32 +0000 |
| Subject: | [php-src] PR #21787: [ext/standard] Specialize array_sum()/array_product() for packed long arrays | ||
| Groups: | php.git-pulls | ||
| Request: | Send a blank email to git-pulls+get-35758@lists.php.net to get a copy of this message | ||
Pull Request: https://github.com/php/php-src/pull/21787
Author: mehmetcansahin
## Summary
array_sum() and array_product() currently dispatch through
add_function() / mul_function() for every element.
This change adds a specialized fast path for packed arrays when both the
accumulator and current element are IS_LONG, inlining overflow-aware
arithmetic via fast_long_add_function() and ZEND_SIGNED_MULTIPLY_LONG().
When those conditions are not met, execution falls back to the existing
generic path through php_array_binop_apply(), preserving current behavior
and warnings for strings, objects, resources, and other non-fast-path values.
This follows the pattern of recent array function optimizations
(#18157, #18158, #18180) and was suggested by @TimWolla during review of
#18180.
## Benchmark
Apple M1, release build (-O2 -DNDEBUG), median of 7 runs. Each benchmark
processes roughly 20M elements total (n * iterations held constant), so the
timings are intended to reflect per-element cost.
| Case | Baseline | Patched | Speedup |
|:--|--:|--:|--:|
| array_sum(range(1, 10000)) | 42.24 ms | 12.99 ms | 3.25x |
| array_product over 10000 small integers (values cycled 0-9) | 144.63 ms | 19.39 ms |
7.46x |
| array_product(range(1, 100)) | 82.94 ms | 58.66 ms | 1.41x |
Packed float arrays, mixed/hash arrays, and pure product on range() stay
approximately neutral.
Mixed IS_LONG / IS_DOUBLE arrays show a small regression from the added
type check before the fast path. Broader fast paths, including IS_DOUBLE
accumulators, were tested but dropped because they caused larger regressions on
mixed and pure-float workloads.
## Testing
- Full ext/standard/tests/array/ suite: 856/856 passing on debug, ZTS, and
release builds.
- Added regression tests:
- array_sum_packed_long_overflow.phpt
- array_product_packed_long_overflow.phpt
- array_sum_product_integration.phpt
All three new tests also pass on current master without the patch, so they
lock in existing semantics rather than implementation details.