在 php5 中使用内联字符串与连接的速度差异? [英] Speed difference in using inline strings vs concatenation in php5?

查看:12
本文介绍了在 php5 中使用内联字符串与连接的速度差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(假设php5)考虑

<?php

    $foo = 'some words';

    //case 1
    print "these are $foo";

    //case 2
    print "these are {$foo}";

    //case 3
    print 'these are ' . $foo;
?>

1 和 2 之间有很大区别吗?

Is there much of a difference between 1 and 2?

如果不是,那么 1/2 到 3 之间呢?

If not, what about between 1/2 and 3?

推荐答案

嗯,就像所有现实生活中什么可能更快"问题一样,您无法通过现实生活测试.

Well, as with all "What might be faster in real life" questions, you can't beat a real life test.

function timeFunc($function, $runs)
{
  $times = array();

  for ($i = 0; $i < $runs; $i++)
  {
    $time = microtime();
    call_user_func($function);
    $times[$i] = microtime() - $time;
  }

  return array_sum($times) / $runs;
}

function Method1()
{ 
  $foo = 'some words';
  for ($i = 0; $i < 10000; $i++)
    $t = "these are $foo";
}

function Method2()
{
  $foo = 'some words';
  for ($i = 0; $i < 10000; $i++)
    $t = "these are {$foo}";
}

function Method3()
 {
  $foo = 'some words';
  for ($i = 0; $i < 10000; $i++)
    $t = "these are " . $foo;
}

print timeFunc('Method1', 10) . "
";
print timeFunc('Method2', 10) . "
";
print timeFunc('Method3', 10) . "
";

运行几次以将所有内容分页,然后...

Give it a few runs to page everything in, then...

0.0035568

0.0035388

0.0025394

因此,正如预期的那样,插值实际上是相同的(噪声级别差异,可能是由于插值引擎需要处理的额外字符).直接串联大约是速度的66%,这不是很大的冲击.插值解析器会查找,发现无事可做,然后以简单的内部字符串 concat 结束.即使 concat 很昂贵,插值器仍然必须这样做,解析出变量并修剪/复制原始字符串的所有工作之后.

So, as expected, the interpolation are virtually identical (noise level differences, probably due to the extra characters the interpolation engine needs to handle). Straight up concatenation is about 66% of the speed, which is no great shock. The interpolation parser will look, find nothing to do, then finish with a simple internal string concat. Even if the concat were expensive, the interpolator will still have to do it, after all the work to parse out the variable and trim/copy up the original string.

Somnath 的更新:

我在上面的实时逻辑中添加了 Method4().

I added Method4() to above real time logic.

function Method4()
 {
  $foo = 'some words';
  for ($i = 0; $i < 10000; $i++)
    $t = 'these are ' . $foo;
}

print timeFunc('Method4', 10) . "
";

Results were:

0.0014739
0.0015574
0.0011955
0.001169

当您只声明一个字符串而无需解析该字符串时,为什么要混淆 PHP 调试器来解析.我希望你明白我的意思.

When you are just declaring a string only and no need to parse that string too, then why to confuse PHP debugger to parse. I hope you got my point.

这篇关于在 php5 中使用内联字符串与连接的速度差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆