【问题标题】:String concatenation in PHP (with a variable inside of it) , which one has a better performance? [closed]PHP中的字符串连接(里面有一个变量),哪个性能更好? [关闭]
【发布时间】:2014-11-28 23:43:55
【问题描述】:

我在 PHP 中有这两个代码:

$msgs = 5;
//These two types of string concatenation

echo 'You got ' . $msgs . ' messages';

echo "You got $msgs messages";

【问题讨论】:

  • 网上有一些地方可以测试这个。对于如此低的迭代,性能差异可以忽略不计。
  • @JayBlanchard 那么哪些地方呢?而不是 - '我,帮助我。
  • 看到这个问题:stackoverflow.com/questions/13620/… :)
  • ——你呢?我不是 - '你。我确实必须询问您是否在 Google 上搜索过此信息,因为您来这里之前似乎没有花任何精力寻找答案。

标签: php performance concatenation string-concatenation


【解决方案1】:

让我们做一些新的测试,很简单

Live example

测试

<?
$str1 = $str2 = "";

for ($i=0; $i < 10000; $i++) {
    $start = microtime(true);
    $str1 .= 'You got ' . $i . ' messages';
    $str1_test[] = microtime(true) - $start;
}

echo "Dotted: " . ($str1_result = array_sum($str1_test) / 10000);

echo PHP_EOL;

for ($i=0; $i < 10000; $i++) {
    $start = microtime(true);
    $str2 .= "You got {$i} messages";
    $str2_test[] = microtime(true) - $start;
}

echo "Interpolated: " . ($str2_result = array_sum($str2_test) / 10000);
echo PHP_EOL . ($str2_result < $str1_result ? "Interpolation" : "Dot") . " is faster!";

结果

Dotted: 1.1234998703003E-6
Interpolated: 1.2600898742676E-6
Dot is faster!

事实

差异小到有意义,我个人喜欢插值,优雅且阅读速度更快,由你决定! ;)

【讨论】:

  • 很好的答案,虽然我会说这里的差异可以忽略不计,但它们会迷失在正常机器操作的背景噪音中;即:差异将在误差范围内。补充一点:在某些情况下,任何一种方法都可以生成更优雅的代码。如果将动态值嵌入文字“模板”字符串中,则插值 - IMO - 更清晰。如果要连接多个字符串:使用连接运算符。使用最适合工作的方法,而不是担心可以忽略的性能因素。
  • @AdamCameron 你是完全正确的。此外,插值不适用于复杂的运算符/表达式:(
  • 是的,这有点麻烦。我只是在学习 PHP(来自 CFML)的过程中,并且经常被它咬伤。 CFML 在这方面比 PHP 更宽容。在这些情况下,我倾向于使用 printf() / sprintf(),但仍然“视情况而定”。
猜你喜欢
  • 1970-01-01
  • 2010-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-11
相关资源
最近更新 更多