Interpolation(直接插入字符串)VS concatenation在性能方面 [英] Interpolation (insert string directly) VS concatenation in the performance aspect
本文介绍了Interpolation(直接插入字符串)VS concatenation在性能方面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
组合 2 个字符串时,以下哪种方法更快?为什么它可以运行得更快?
Which is below method is faster when combining 2 strings ? And why can it run faster?
PHP 代码:
$str1 = 'Hello';
$str2 = 'World';
方法一:
$txt = $str1.$str2;
方法二:
$txt = "$str1$str2";
推荐答案
操作码对比
代码:
$a=1;
$b=2;
echo "$a$b";
操作码:
1 0 > ASSIGN !0, 1
1 ASSIGN !1, 2
2 ADD_VAR ~2 !0
3 ADD_VAR ~2 ~2, !1
4 ECHO ~2
5 > RETURN null
代码:
$a=1;
$b=2;
echo $a.$b;
操作码:
1 0 > ASSIGN !0, 1
1 ASSIGN !1, 2
2 CONCAT ~2 !0, !1
3 ECHO ~2
4 > RETURN null
中间结论
连接少了一个操作码,欢欣鼓舞!不是真的,我们仍然需要测试实际的运行时性能.
Concatenation has one less opcode, rejoice! Not really, we still have to test the actual runtime performance.
要查看任何一段代码生成的操作码,请查看很棒的 vld
扩展
To see the opcodes generated by any piece of code, have a look at the great vld
extension
运行时性能
在工作站上运行超过 0.5m 次迭代(平均运行超过 10 次):
Ran over 0.5m iterations on a workstation (average over 10 runs):
- 内联:0.9793s
- 串联:0.9252s
结论
串联速度更快,但不太可能影响任何特定应用程序的性能.
Concatenation is faster, though it's unlikely to impact the performance of any particular application.
这篇关于Interpolation(直接插入字符串)VS concatenation在性能方面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文