PHP字符串连接 - "$ a $ b"vs $ a."".$ b - 表现

J. *_*ver 4 php string performance concatenation

是否有速度差异,比如:

$ newstring ="$ a和$ b出去看$ c";

$ newstring = $ a."和".$ b."出去看看".$ C;

如果是这样,为什么?

Mar*_*urz 16

根据 PHP版本的不同,如果您将其编写为以下内容,则第二个更快的速度会有所不同: $newstring = $a . ' and ' . $b . ' went out to see ' . $c;

PHP 在版本之间非常不一致,并且在性能方面进行构建,您必须自己测试它.需要说的是,它还取决于类型$a,$b并且$c如下所示.

当你使用时",PHP解析字符串以查看其中是否有任何变量/占位符,但如果你只使用'PHP,则将其视为一个简单的字符串,无需进一步处理.所以一般'应该更快.至少在理论上.在实践中你必须测试.


结果(以秒为单位):

a, b, c are integers:
all inside "     : 1.2370789051056
split up using " : 1.2362520694733
split up using ' : 1.2344131469727

a, b, c are strings:
all inside "     : 0.67671513557434
split up using " : 0.7719099521637
split up using ' : 0.78600907325745  <--- this is always the slowest in the group. PHP, 'nough said
Run Code Online (Sandbox Code Playgroud)

在Zend Server CE PHP 5.3中使用此代码:

<?php

echo 'a, b, c are integers:<br />';
$a = $b = $c = 123;

$t = xdebug_time_index();
for($i = 1000000; $i > 0; $i--)
    $newstring = "$a and $b went out to see $c";
$t = xdebug_time_index() - $t;
echo 'all inside " : ', $t, '<br />';

$t = xdebug_time_index();
for($i = 1000000; $i > 0; $i--)
    $newstring = $a . " and " . $b . " went out to see " . $c;
$t = xdebug_time_index() - $t;
echo 'split up using " : ', $t, '<br />';

$t = xdebug_time_index();
for($i = 1000000; $i > 0; $i--)
    $newstring = $a . ' and ' . $b . ' went out to see ' . $c;
$t = xdebug_time_index() - $t;
echo 'split up using \' : ', $t, '<br /><br />a, b, c are strings:<br />';

$a = $b = $c = '123';

$t = xdebug_time_index();
for($i = 1000000; $i > 0; $i--)
    $newstring = "$a and $b went out to see $c";
$t = xdebug_time_index() - $t;
echo 'all inside " : ', $t, '<br />';

$t = xdebug_time_index();
for($i = 1000000; $i > 0; $i--)
    $newstring = $a . " and " . $b . " went out to see " . $c;
$t = xdebug_time_index() - $t;
echo 'split up using " : ', $t, '<br />';

$t = xdebug_time_index();
for($i = 1000000; $i > 0; $i--)
    $newstring = $a . ' and ' . $b . ' went out to see ' . $c;
$t = xdebug_time_index() - $t;
echo 'split up using \' : ', $t, '<br />';

?>
Run Code Online (Sandbox Code Playgroud)


Sam*_*son 6

可能存在速度差异,因为它有两种不同的语法.你需要问的是差异是否重要.在这种情况下,不,我认为你不必担心.差异可以忽略不计.

我建议你做一些视觉上最有意义的事情." $a and $b went out to see $c"看起来有点令人困惑.如果你想走那条路,我建议围绕你的变量大括号:" {$a} and {$b} went out to see {$c}".