php 在 php5 中使用内联字符串与连接的速度差异?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13620/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 21:11:21  来源:igfitidea点击:

Speed difference in using inline strings vs concatenation in php5?

phpoptimizationperformance

提问by Uberfuzzy

(assume php5) consider

(假设php5)考虑

<?php

    $foo = 'some words';

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

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

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

Is there much of a difference between 1 and 2?

1和2差别大吗?

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

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

采纳答案by Adam Wright

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) . "\n";
print timeFunc('Method2', 10) . "\n";
print timeFunc('Method3', 10) . "\n";

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

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

0.0035568

0.0035568

0.0035388

0.0035388

0.0025394

0.0025394

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, afterall the work to parse out the variable and trim/copy up the original string.

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

Updates By Somnath:

Somnath 的更新:

I added Method4() to above real time logic.

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

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

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

Results were:

0.0014739
0.0015574
0.0011955
0.001169

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.

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

回答by Paolo Bergantino

The performance difference has been irrelevantsince at least January 2012, and likely earlier:

至少从 2012 年 1 月起,性能差异就变得无关紧要了,而且可能更早:

Single quotes: 0.061846971511841 seconds
Double quotes: 0.061599016189575 seconds

Earlier versions of PHP may have had a difference - I personally prefer single quotes to double quotes, so it was a convenient difference. The conclusion of the article makes an excellent point:

早期版本的 PHP 可能有所不同 - 我个人更喜欢单引号而不是双引号,所以这是一个方便的区别。文章的结论提出了一个很好的观点:

Never trust a statistic you didn't forge yourself.

永远不要相信一个不是你自己伪造的统计数据。

(Although the article quotes the phrase, the original quip was likely falsely attributedto Winston Churchill, invented by Joseph Goebbels' propaganda ministry to portray Churchill as a liar:

(虽然文章引用了这句话,但最初的讽刺很可能被错误地归因于温斯顿·丘吉尔,由约瑟夫·戈培尔的宣传部发明,将丘吉尔描绘成骗子:

Ich traue keiner Statistik, die ich nicht selbst gef?lscht habe.

Ich traue keiner Statistik, die ich nicht selbst gef?lscht habe。

This loosely translates to, "I do not trust a statistic that I did not fake myself.")

这松散地翻译为,“我不相信我没有伪造自己的统计数据。”)

回答by Mike B

Live benchmarks:

实时基准:

http://phpbench.com/

http://phpbench.com/

There is actually a subtle difference when concatenating variables with single vs double quotes.

使用单引号和双引号连接变量时实际上存在细微差别。

回答by Pierre Spring

@Adam's test used

使用@Adam 的测试

"these are " . $foo

note that the following is even faster:

请注意,以下更快:

'these are ' . $foo;

this is due to the fact, that a double quoted "string" gets evaluated, where a single quoted 'string' is just taken as is...

这是由于这样一个事实,即对双引号“字符串”进行了评估,其中单引号“字符串”只是按原样使用...

回答by Jake McGraw

Don't get too caught up on trying to optimize string operations in PHP. Concatenation vs. interpolation is meaningless (in real world performance) if your database queries are poorly written or you aren't using any kind of caching scheme. Write your string operations in such a way that debugging your code later will be easy, the performance differences are negligible.

不要太忙于尝试优化 PHP 中的字符串操作。如果您的数据库查询写得不好或者您没有使用任何类型的缓存方案,则串联与插值是没有意义的(在现实世界的性能中)。以这样一种方式编写字符串操作,以便以后调试代码很容易,性能差异可以忽略不计。

@uberfuzzy Assuming this is just a question about language minutia, I suppose it's fine. I'm just trying to add to the conversation that comparing performance between single-quote, double-quote and heredoc in real world applications in meaningless when compared to the real performance sinks, such as poor database queries.

@uberfuzzy 假设这只是一个关于语言细节的问题,我想这很好。我只是想添加到对话中,与实际性能接收器(例如较差的数据库查询)相比,在现实世界应用程序中比较单引号、双引号和heredoc 之间的性能毫无意义。

回答by Gordon

Any differences in execution time are completely negligible.

执行时间的任何差异完全可以忽略不计。

Please see

请参见

Don't waste time on micro-optimizations like this. Use a profiler to measure the performance of your application in a real world scenario and then optimize where it is really needed. Optimising a single sloppy DB query is likely to make a bigger performance improvement than applying micro-optimisations all over your code.

不要在这样的微优化上浪费时间。使用分析器在真实场景中测量应用程序的性能,然后在真正需要的地方进行优化。与在整个代码中应用微优化相比,优化单个草率数据库查询可能会带来更大的性能提升。

回答by Gordon

there is a difference when concatenating variables... and what you are doing with the result... and if what you are doing is dumping it to output, is or isn't output buffering on.

连接变量时会有所不同......以及您对结果所做的事情......如果您正在做的是将其转储到输出,则是或不是输出缓冲。

also, what is the memory situation of the server? typically memory management on a higher level platform is worse than that at lower platforms...

另外,服务器的内存情况如何?通常,较高级别平台上的内存管理比较低平台上的内存管理更差...

$a = 'parse' . $this; 

is managing memory at the user code platform level...

正在用户代码平台级别管理内存...

$a = "parse $this";

is managing memory at the php system code platform level...

正在php系统代码平台级别管理内存...

so these benchmarks as related to CPU don't tell the full story.

所以这些与 CPU 相关的基准测试并不能说明全部情况。

running the benchmark 1000 times vs running the benchmark 1000 times on a server that is attempting to run that same simulation 1000 times concurrently... you might get drastically different results depending on the scope of the application.

运行基准测试 1000 次与在尝试同时运行相同模拟 1000 次的服务器上运行基准测试 1000 次……根据应用程序的范围,您可能会得到截然不同的结果。

回答by navitronic

I seem to remember that the developer of the forum software, Vanilla replaced all the double quotes in his code with single quotes and noticed a reasonable amount of performance increase.

我似乎记得论坛软件的开发者 Vanilla 用单引号替换了他代码中的所有双引号,并注意到了合理的性能提升。

I can't seem to track down a link to the discussion at the moment though.

不过,我目前似乎无法找到讨论的链接。

回答by kimsk

Double quotes can be much slower. I read from several places that that it is better to do this

双引号可能会慢得多。我从几个地方读到最好这样做

'parse me '.$i.' times'

than

"parse me $i times"

Although I'd say the second one gave you more readable code.

虽然我会说第二个给了你更多可读的代码。

回答by Rob Forrest

Just to add something else to the mix, if you are using a variable inside a double quoted string syntax:

如果您在双引号字符串语法中使用变量,只需添加其他内容:

$foo = "hello {$bar}";

is faster than

$foo = "hello $bar";

and both of these are faster than

这两个都比

$foo = 'hello' . $bar;