Skip to content

Optimize array_diff() for long values#22648

Open
mehmetcansahin wants to merge 1 commit into
php:masterfrom
mehmetcansahin:array-diff-long-fast-path
Open

Optimize array_diff() for long values#22648
mehmetcansahin wants to merge 1 commit into
php:masterfrom
mehmetcansahin:array-diff-long-fast-path

Conversation

@mehmetcansahin

Copy link
Copy Markdown
Contributor

Summary

This adds a fast path for array_diff() when all compared values are integers. Instead of converting values to temporary strings, the implementation builds an integer-keyed exclude map and copies values from the first array when they are not present in that map.

Mixed-type inputs still fall back to the existing generic implementation, preserving current comparison behavior.

Benchmark

$a = range(0, 200000);
$b = range(100000, 300000);

$start = microtime(true);
for ($i = 0; $i < 10; $i++) {
    array_diff($a, $b);
}
printf("%.3fs\n", microtime(true) - $start);

Before: ~0.12s, after: ~0.024s (~5x faster).

Tests

  • make -j8
  • ./sapi/cli/php run-tests.php -n -q ext/standard/tests/array/array_diff*.phpt (50/50 pass)

The new test covers integer values, negative values, min/max integers, duplicate values, key preservation, string fallback cases, multiple exclude arrays, references, and empty results.

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.

1 participant