PHP字符串连接 - “$ a $ b”vs $ a。 “”。 $ b - 表现
-
06-07-2019 - |
题
之间是否有速度差异,比如说:
$ newstring =" $ a和$ b出去看$ c&quot ;;
和
$ newstring = $ a。 "和“ 。 $ b。 "出去看看“ 。 $ C;
如果有,为什么?
解决方案
取决于在PHP版本上,如果您将其编写为:
$ newstring = $ a。 '和'。 $ b。 '出去看'。 $ C; 代码>
$ 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和$ b出去看$ c
&quot;看着它可能有点混乱。如果你想走那条路,我会建议围绕你的变量大括号:“ {$ a}和{$ b}去看{$ c}
&quot;。
我做了一个快速的基准测试,正如其他人所说,结果非常不一致。我没有注意到使用单引号而不是双引号的性能提升。我猜这一切都归结为偏好。
您可能希望坚持使用一种类型的引用来编写您的编码风格,如果您这样做,请选择双引号。替换功能比您想象的更频繁。
我将基准代码放在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等)和使用单引号时,它不会解析变量或特殊字符,因此速度可能略有增加。
为什么不测试它,并比较差异?数字不是谎言,如果你发现一个表现得比另一个好,那么你应该问为什么。
没有区别,期间。 ;)