Skip to content

Zend: Optimize sorting single-element arrays - #23550

Open
LamentXU123 wants to merge 1 commit into
php:masterfrom
LamentXU123:packed
Open

Zend: Optimize sorting single-element arrays#23550
LamentXU123 wants to merge 1 commit into
php:masterfrom
LamentXU123:packed

Conversation

@LamentXU123

@LamentXU123 LamentXU123 commented Sep 3, 2026

Copy link
Copy Markdown
Member

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.

Some may ask what's the meaning to sort one-element array anyways. This can't be similar to what sorting zero-element array do, which is directly returning the empty array. Because the sorting functions have other things to do rather than just sort the elements.

<?php
$array = ['key' => 42];
sort($array);

var_dump($array);
// [0 => 42]

Here, we remain the original sort behavior for one-element array while making it faster because we are not actually sorting them

benchmark results:

After: 448.923 ms
Before: 905.807 ms
a roughly 50.4% enhancement in this specific case.

script:

<?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,
);

@devnexen

devnexen commented Sep 3, 2026

Copy link
Copy Markdown
Member

unless Gina beats me to it, I ll review a bit later seems good not entirely sure it s bug free

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants