Skip to content

Commit 2a9b80f

Browse files
committed
Improve performance of array_walk()
We never need to use refcounted copies for arguments because the copy to the call frame already increments the refcount. For the following benchmark: ```php $a = range(0, 10); for ($i = 0; $i < 1000000; $i++) array_walk($a, fn ($val, $idx, $arg) => $val + $arg, 2); ``` On an i7-4790: ``` Benchmark 1: ./sapi/cli/php x.php Time (mean ± σ): 593.0 ms ± 5.4 ms [User: 589.8 ms, System: 1.7 ms] Range (min … max): 583.3 ms … 600.9 ms 10 runs Benchmark 2: ./sapi/cli/php_old x.php Time (mean ± σ): 637.8 ms ± 4.6 ms [User: 633.9 ms, System: 2.2 ms] Range (min … max): 633.4 ms … 649.2 ms 10 runs Summary ./sapi/cli/php x.php ran 1.08 ± 0.01 times faster than ./sapi/cli/php_old x.php ``` On an i7-1185G7: ``` Benchmark 1: ./sapi/cli/php x.php Time (mean ± σ): 362.3 ms ± 2.0 ms [User: 359.9 ms, System: 1.9 ms] Range (min … max): 359.6 ms … 367.1 ms 10 runs Benchmark 2: ./sapi/cli/php_old x.php Time (mean ± σ): 385.5 ms ± 1.8 ms [User: 383.2 ms, System: 1.9 ms] Range (min … max): 381.5 ms … 387.2 ms 10 runs Summary ./sapi/cli/php x.php ran 1.06 ± 0.01 times faster than ./sapi/cli/php_old x.php ```
1 parent 455893e commit 2a9b80f

File tree

1 file changed

+3
-11
lines changed

1 file changed

+3
-11
lines changed

ext/standard/array.c

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1457,7 +1457,7 @@ static zend_result php_array_walk(
14571457
/* Set up known arguments */
14581458
ZVAL_UNDEF(&args[1]);
14591459
if (userdata) {
1460-
ZVAL_COPY(&args[2], userdata);
1460+
ZVAL_COPY_VALUE(&args[2], userdata);
14611461
}
14621462

14631463
fci.retval = &retval;
@@ -1531,21 +1531,16 @@ static zend_result php_array_walk(
15311531
}
15321532
zval_ptr_dtor(&ref);
15331533
} else {
1534-
ZVAL_COPY(&args[0], zv);
1534+
ZVAL_COPY_VALUE(&args[0], zv);
15351535

15361536
/* Call the userland function */
15371537
result = zend_call_function(&fci, &context->fci_cache);
15381538
if (result == SUCCESS) {
15391539
zval_ptr_dtor(&retval);
15401540
}
1541-
1542-
zval_ptr_dtor(&args[0]);
15431541
}
15441542

1545-
if (Z_TYPE(args[1]) != IS_UNDEF) {
1546-
zval_ptr_dtor(&args[1]);
1547-
ZVAL_UNDEF(&args[1]);
1548-
}
1543+
zval_ptr_dtor_str(&args[1]);
15491544

15501545
if (result == FAILURE) {
15511546
break;
@@ -1565,9 +1560,6 @@ static zend_result php_array_walk(
15651560
}
15661561
} while (!EG(exception));
15671562

1568-
if (userdata) {
1569-
zval_ptr_dtor(&args[2]);
1570-
}
15711563
zend_hash_iterator_del(ht_iter);
15721564
return result;
15731565
}

0 commit comments

Comments
 (0)