PHP 字符串连接 - "$a $b"与 $a 。 ""。 $b - 性能

标签 php performance string concatenation

之间是否存在速度差异,例如:

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

$newstring = $a . “和 ” 。 $b。 “出去看看”。 $c;

如果是,为什么?

最佳答案

取决于 PHP 版本,如果您这样写,它会随着秒数的增加而变化: $newstring = $a . ' 和 ' 。 $b。 '出去看看'。 $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 />';

?>

关于PHP 字符串连接 - "$a $b"与 $a 。 ""。 $b - 性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1813673/

相关文章:

javascript - PHP-从基于另一个下拉列表的数据插入

performance - 当内存中数据网格优于 NoSQL/NoSQL + 分布式缓存时

python - 在 Python 中连接由空行分隔的行

c# - Codedom 和字符串处理

C: ???正在添加到 sizeof(string) 之外的我的字符串中

php - 如何从 mysql 查询中获取所有相关类别列表

php - 如何将 1,300.00 更改为 1300,00

php - Laravel 助手接口(interface)

performance - 对于大于 32kb 的文件,BLOB 导出速度很慢

c++ vector 性能非直观结果?