在以下两种方式中,是否存在速度差异:
$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";
和
$newstring = $a . " and " . $b . " went out to see " . $c;
如果存在差异,为什么呢?
$newstring = $a . ' and ' . $b . ' went out to see ' . $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 and $b went out to see $c
" 在查看时可能会有点混淆。如果您想走这条路,我建议在变量周围加上花括号: "{$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;
如果你使用了:
$newstring = $a . ' and ' . $b . ' went out to see ' . $c;
差别会略微大一些(但可能仍然可以忽略不计),原因是,如果我记得正确的话(我可能在这方面弄错了),PHP会扫描和解析双引号内的变量和特殊字符(\t、\n等),而在使用单引号时它不会解析变量或特殊字符,因此速度可能会略微提高。
为什么不测试一下,比较一下差异呢?数字不会说谎,如果你发现其中一个表现更好,那么你应该问问为什么。
没有任何区别,就是这样。 ;)