- URL: https://www.laruence.com/en/2011/11/04/2258.html
- Please include attribution when republishing.
In PHP 5.4, Arnaud introduced an optimization for the ternary operator.
We all know that PHP uses copy-on-write to optimize the performance of variable copying. But in the old ternary operator, it would copy every single time, which causes a performance problem when the operand is a large array:
<?php
$a = range(1, 1000);
$i = 0;
$start = microtime(true);
while (++$i < 1000) {
$b = isset($a)? $a : NULL;
}
var_dump(microtime(true) - $start);
By contrast, if we use if-else to do the same thing:
<?php
$a = range(1, 1000);
$i = 0;
$start = microtime(true);
while (++$i < 1000) {
if (isset($a)) {
$b = $a;
} else {
$b = NULL;
}
}
var_dump(microtime(true) - $start);
On my machine, the former took: float(0.0448620319366), while if-else took: float(0.000280006027222)
To this end, Arnaud provided a patch to optimize the ternary operator, so that the ternary no longer copies its operand every time. After the optimization, the runtime of the example at the beginning dropped to: float(0.00029182434082031)
The ternary operator always copies its second or third operand, which is very
slow compared to an if/else when the operand is an array for example:
$a = range(0,9);
// this takes 0.3 seconds here:
for ($i = 0; $i < 5000000; ++$i) { if (true) { $b = $a; } else { $b = $a; } } // this takes 3.8 seconds: for ($i = 0; $i < 5000000; ++$i) { $b = true ? $a : $a; } I've tried to reduce the performance hit by avoiding the copy when possible (patch attached). Benchmark: Without patch: (the numbers are the time taken to run the code a certain amount of times) $int = 0; $ary = array(1,2,3,4,5,6,7,8,9); true ? 1 : 0 0.124 true ? 1+0 : 0 0.109 true ? $ary : 0 2.020 ! true ? $int : 0 0.103 true ? ${'ary'} : 0 2.290 ! true ?: 0 0.091 1+0 ?: 0 0.086 $ary ?: 0 2.151 ! ${'var'} ?: 0 2.317 ! With patch: true ? 1 : 0 0.124 true ? 1+0 : 0 0.195 true ? $ary : 0 0.103 true ? $int : 0 0.089 true ? ${'ary'} : 0 0.103 true ?: 0 0.086 1+0 ?: 0 0.159 $cv ?: 0 0.090 ${'var'} ?: 0 0.089 The array copying overhead is eliminated. There is however a slowdown in some of the cases, but overall there is no completely unexpected performance hit as it is the case currently.
That said, a reminder: PHP 5.4 is still under development. Before the final release, any new feature may be adjusted or changed. If you have any suggestions, feedback is welcome, to help make PHP even better.
Thanks
For more updates, follow: Changelog
Be First to Comment