21,880
社区成员
发帖
与我相关
我的任务
分享
$_bpt;
function BeginProfile($text = null)
{
global $_bpt;
if($text !== null)
echo $text, ': ';
$_bpt = microtime(true);
}
function EndProfile()
{
global $_bpt;
echo microtime(true) - $_bpt, PHP_EOL;
}
function test1($a, $b)
{
echo '[test1] a: ', $a, ' b: ', $b, PHP_EOL;
$r = null;
$i = null;
BeginProfile('if');
for($i = 0; $i < 10000000; ++$i)
if($a > $b)
$r = $a;
else
$r = $b;
EndProfile();
BeginProfile('ternary');
for($i = 0; $i < 10000000; ++$i)
$r = $a > $b ? $a : $b;
EndProfile();
echo PHP_EOL;
}
function test2($a, $b)
{
echo '[test2] a: ', $a, ' b: ', $b, PHP_EOL;
$r = null;
$i = null;
BeginProfile('if');
for($i = 0; $i < 10000000; ++$i)
if($a > $b)
$r = 1;
else
$r = -1;
EndProfile();
BeginProfile('ternary');
for($i = 0; $i < 10000000; ++$i)
$r = $a > $b ? 1 : -1;
EndProfile();
echo PHP_EOL;
}
test1(0, 1);
test1(1, 0);
test2(0, 1);
test2(1, 0);
[test1] a: 0 b: 1
if: 0.40560913085938
ternary: 0.47002696990967
[test1] a: 1 b: 0
if: 0.69283294677734
ternary: 0.65520095825195
[test2] a: 0 b: 1
if: 0.3744010925293
ternary: 0.5928008556366
[test2] a: 1 b: 0
if: 0.59280109405518
ternary: 0.71760106086731
[test1] a: 0 b: 1
if: 0.89750385284424
ternary: 0.76072287559509
[test1] a: 1 b: 0
if: 1.1494359970093
ternary: 0.78078508377075
[test2] a: 0 b: 1
if: 0.68948316574097
ternary: 0.99170303344727
[test2] a: 1 b: 0
if: 1.0860159397125
ternary: 1.4367680549622
if($a > $b) $r = $a; else $r = $b;
$r = $a > $b ? $a : $b;
这种情况if效率高
if($a > $b) $r = 1; else $r = -1;
$r = $a > $b ? 1 : -1;
我想知道的是为什么,不是观察结果