Interpolation (insert string directly) VS concatenation in the performance aspect [closed]

此生再无相见时 提交于 2019-12-10 17:49:55

问题


Which is below method is faster when combining 2 strings ? And why can it run faster?

PHP code:

$str1 = 'Hello';
$str2 = 'World';

method 1:

$txt = $str1.$str2;

method 2:

$txt = "$str1$str2";

回答1:


Opcode comparison

Code:

$a=1; 
$b=2; 
echo "$a$b";

Opcodes:

   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

Code:

$a=1; 
$b=2; 
echo $a.$b;

Opcodes:

   1     0  >   ASSIGN                                                   !0, 1
         1      ASSIGN                                                   !1, 2
         2      CONCAT                                           ~2      !0, !1
         3      ECHO                                                     ~2
         4    > RETURN                                                   null

Intermediate conclusion

Concatenation has one less opcode, rejoice! Not really, we still have to test the actual runtime performance.

To see the opcodes generated by any piece of code, have a look at the great vld extension

Runtime performance

Ran over 0.5m iterations on a workstation (average over 10 runs):

  • Inlined: 0.9793s
  • Concatenated: 0.9252s

Conclusion

Concatenation is faster, though it's unlikely to impact the performance of any particular application.



来源:https://stackoverflow.com/questions/13553402/interpolation-insert-string-directly-vs-concatenation-in-the-performance-aspec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!