【发布时间】:2010-12-21 06:49:00
【问题描述】:
是否有速度差异,比如说:
$newstring = "$a和$b出去看$c";
和
$newstring = $a 。 “ 和 ” 。 $b 。 “出去看看”。 $c;
如果是这样,为什么?
【问题讨论】:
标签: php performance string concatenation
是否有速度差异,比如说:
$newstring = "$a和$b出去看$c";
和
$newstring = $a 。 “ 和 ” 。 $b 。 “出去看看”。 $c;
如果是这样,为什么?
【问题讨论】:
标签: php performance string concatenation
取决于 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
将此代码与 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 />';
?>
【讨论】:
可能会有速度差异,因为它是两种不同的语法。您需要问的是差异是否重要。在这种情况下,不,我认为你不必担心。差别太小了。
我建议你做任何对你最有意义的事情。 “$a and $b went out to see $c”在查看时可能会有些混乱。如果您想走那条路,我建议您在变量周围加上花括号:“{$a} and {$b} went out to see {$c}”。
【讨论】:
我做了一个快速基准测试,正如其他人所说,结果非常不一致。我没有注意到使用单引号而不是双引号的任何性能提升。我的猜测是,这一切都归结为偏好。
您可能希望根据自己的编码风格坚持使用一种引号,如果这样做,请选择双引号。替换功能比您想象的更容易派上用场。
我把基准代码on github.
【讨论】:
如果您担心此级别的字符串连接速度,则说明您使用了错误的语言。为这个用例用 C 编译一个应用程序并在你的 PHP 脚本中调用它,如果这个 真的 是一个瓶颈。
【讨论】:
是的,但是两者之间的差异可以忽略不计
$newstring = "$a and $b went out to see $c";
和
$newstring = $a . " and " . $b . " went out to see " . $c;
如果你使用过:
$newstring = $a . ' and ' . $b . ' went out to see ' . $c;
差异会稍微大一些(但可能仍然可以忽略不计),原因是,如果我没记错的话(我可能错了),PHP 会扫描并解析双引号内的变量和特殊内容字符(\t、\n 等),当使用单引号时,它不会解析变量或特殊字符,因此速度可能会略有提高。
【讨论】:
你为什么不测试一下,比较一下区别?数字不会说谎,如果你发现一个比另一个表现更好,那么你应该问为什么。
【讨论】:
没有区别,句号。 ;)
【讨论】: