Skip to content

Conversation

@ndossche
Copy link
Member

@ndossche ndossche commented Nov 1, 2025

Packed arrays are likely common in this case, as with array_shift which already has a similar optimization.

For the following benchmark:

<?php

for ($i = 0; $i < 10000000; $i++) {
    $a = [0, 1, 2, 3, 4, 5];
    array_unshift($a, -3, -2, -1);
}

On an i7-4790:

Benchmark 1: ./sapi/cli/php x.php
  Time (mean ± σ):     753.8 ms ±  23.8 ms    [User: 749.8 ms, System: 2.1 ms]
  Range (min … max):   734.3 ms … 818.6 ms    10 runs

Benchmark 2: ./sapi/cli/php_old x.php
  Time (mean ± σ):     972.5 ms ±   5.0 ms    [User: 968.8 ms, System: 1.4 ms]
  Range (min … max):   967.8 ms … 984.3 ms    10 runs

Summary
  ./sapi/cli/php x.php  ran
    1.29 ± 0.04 times faster than ./sapi/cli/php_old x.php

On an i7-1185G7:

Benchmark 1: ./sapi/cli/php x.php
  Time (mean ± σ):     507.9 ms ±   6.7 ms    [User: 504.7 ms, System: 2.6 ms]
  Range (min … max):   498.3 ms … 519.3 ms    10 runs
 
Benchmark 2: ./sapi/cli/php_old x.php
  Time (mean ± σ):     627.1 ms ±   7.2 ms    [User: 624.0 ms, System: 2.3 ms]
  Range (min … max):   616.6 ms … 640.2 ms    10 runs
 
Summary
  ./sapi/cli/php x.php ran
    1.23 ± 0.02 times faster than ./sapi/cli/php_old x.php

@ndossche ndossche marked this pull request as ready for review November 1, 2025 10:11
@ndossche ndossche requested a review from bukka as a code owner November 1, 2025 10:11
Copy link
Member

@iluuu1994 iluuu1994 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks correct

Packed arrays are likely common in this case, as with array_shift which
already has a similar optimization.

For the following benchmark:
```php
<?php

for ($i = 0; $i < 10000000; $i++) {
    $a = [0, 1, 2, 3, 4, 5];
    array_unshift($a, -3, -2, -1);
}
```

On an i7-4790:
```
Benchmark 1: ./sapi/cli/php x.php
  Time (mean ± σ):     753.8 ms ±  23.8 ms    [User: 749.8 ms, System: 2.1 ms]
  Range (min … max):   734.3 ms … 818.6 ms    10 runs

Benchmark 2: ./sapi/cli/php_old x.php
  Time (mean ± σ):     972.5 ms ±   5.0 ms    [User: 968.8 ms, System: 1.4 ms]
  Range (min … max):   967.8 ms … 984.3 ms    10 runs

Summary
  ./sapi/cli/php x.php  ran
    1.29 ± 0.04 times faster than ./sapi/cli/php_old x.php
```
@ndossche ndossche force-pushed the array-unshift-packed branch from cc04158 to 2850711 Compare November 6, 2025 17:49
@ndossche ndossche merged commit db8c331 into php:master Nov 6, 2025
1 check passed
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.

3 participants