首页 > php教程 > php手册 > 正文

PHP 5.4 由Arnaud 引入了一个对三元式的优化方案.

php中文网
发布: 2016-06-21 08:52:53
原创
943人浏览过

 

我们都知道PHP用写时复制来对变量复制做性能优化, 而在以前的三元式中, 却每次都会复制, 这在操作数是大数组的情况下, 会造成性能问题:

$a = range(1, 1000);
$i = 0;

$start = microtime(true);
while (++$i $b = isset($a)? $a : NULL;
}

var_dump(microtime(true) - $start);
相比, 我们采用if-else来做同样的功能:

$a = range(1, 1000);
$i = 0;

$start = microtime(true);
while (++$i 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 if (true) {
$b = $a;
} else {
$b = $a;
}
}

// this takes 3.8 seconds:

for ($i = 0; $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.

不过, 还是要提醒下: PHP 5.4还处于开发阶段, 在最终release之前, 任何新特性都可能被调整或者更改. 如果大家有任何建议, 也欢迎反馈, 帮助我们使得PHP变得更好.

谢谢



PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号