PHP点运算符和双引号变量替换的性能比较
更新:HHH   时间:2023-1-7


【测试环境】

windows 8.1

wampserver 2.4

总共循环10次,每次测试1000000次,计算出每次循环的时间和总的时间,并且算出平均值


【测试代码】

点运算符性能测试代码:

$total = 1000000;
$loop = 10;
$a = '123';
$b = '456';
$c = '789';
$str = '';
$total_spend = 0;
for ($num=1; $num<=$loop; $num++) {
    $start = microtime(true);
    for ($i=0; $i<$total; $i++) {
        $str = $a . $b . $c;
    }
    $end = microtime(true);
    $spend = $end - $start;
    echo "loop $num: " . $spend .'<br/>';
    $total_spend += $spend;
}
$avg = $total_spend / $loop;
echo 'average spend: ' . $avg . '<br>';


双引号变量替换性能测试代码:

$total = 1000000;
$loop = 10;
$a = '123';
$b = '456';
$c = '789';
$str = '';
$total_spend = 0;
for ($num=1; $num<=$loop; $num++) {
    $start = microtime(true);
    for ($i=0; $i<$total; $i++) {
        $str = "{$a}{$b}{$c}";
    }
    $end = microtime(true);
    $spend = $end - $start;
    echo "loop $num: " . $spend .'<br/>';
    $total_spend += $spend;
}
$avg = $total_spend / $loop;
echo 'average spend: ' . $avg . '<br>';


【测试结果】

点运算符:

双引号变量替换:


【结论】

在php中,双引号变量替换的性能比点运算符的性能要好。


返回web开发教程...