您的位置:首页 > 编程语言 > PHP开发

三元式(ternary)性能优化

2011-11-04 00:00 1256 查看
PHP 5.4 由Arnaud 引入了一个对三元式的优化方案.
我们都知道PHP用写时复制来对变量复制做性能优化, 而在以前的三元式中, 却每次都会复制, 这在操作数是大数组的情况下, 会造成性能问题:
<?php$a = range(1, 1000);$i = 0;$start = microtime(true);while (++$i < 1000) {    $b = isset($a)? $a : NULL;}var_dump(microtime(true) - $start);
相比, 我们采用if-else来做同样的功能:
<?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);
前者在我的机器上, 运行时间为: float(0.0448620319366), 而采用if-else则是: float(0.000280006027222)
为此, Arnaud提供了一个patch, 来对三元式做了一个优化, 使得三元式不会每次都复制操作数, 在优化以后, 开头给的例子的运行时间降低为: 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
不过, 还是要提醒下: PHP 5.4还处于开发阶段, 在最终release之前, 任何新特性都可能被调整或者更改. 如果大家有任何建议, 也欢迎反馈, 帮助我们使得PHP变得更好.
谢谢
更多更新信息, 请关注:Changelog
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息