在php5中使用内联字符串与串联的速度差异? [英] Speed difference in using inline strings vs concatenation in 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) . "\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
因此,正如预期的那样,插值实际上是相同的(噪声级别差异,可能是由于插值引擎需要处理的额外字符).直线连接的速度约为速度的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) . "\n";
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屋!