[php-src] PR #23550: Zend: Optimize sorting single-element arrays
| From: | LamentXU123 | Date: | Thu, 03 Sep 2026 04:39:26 +0000 |
| Subject: | [php-src] PR #23550: Zend: Optimize sorting single-element arrays | ||
| Groups: | php.git-pulls | ||
| Request: | Send a blank email to git-pulls+get-38273@lists.php.net to get a copy of this message | ||
Pull Request: https://github.com/php/php-src/pull/23550
Author: LamentXU123
Now,
zend_array_sort() uses zend_array_sort_ex(), which unpacks packed
arrays and temporarily increments the array refcount to protect against the comparator freeing the
array.
Obviously this is useless for one-element arrays. Here, we can just use
zend_hash_sort_ex instead for this case.
benchmark results:
After: 448.923 ms
Before: 905.807 ms
a roughly 50.4% enhancement in this specific case.
script:
```php
<?php
const ITERATIONS = 20_000_000;
const RUNS = 7;
function run(int $iterations): float
{
$array = [42];
$start = hrtime(true);
for ($i = 0; $i < $iterations; $i++) {
sort($array, SORT_NUMERIC);
}
return (hrtime(true) - $start) / 1e6;
}
run(100_000); // Warmup
$times = [];
for ($run = 0; $run < RUNS; $run++) {
$times[] = run(ITERATIONS);
}
sort($times, SORT_NUMERIC);
$median = $times[intdiv(RUNS, 2)];
printf(
"single-element sort: %.3f ms (%d iterations, median of %d)\n",
$median,
ITERATIONS,
RUNS,
);
```