3

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";
hakre
  • 193,403
  • 52
  • 435
  • 836
  • 1
    Build a benchmark test and test it yourself. – Gumbo Nov 25 '12 at 17:26
  • possible duplicate of [Speed difference in using inline strings vs concatenation in php5?](http://stackoverflow.com/questions/13620/speed-difference-in-using-inline-strings-vs-concatenation-in-php5) – Michael Berkowski Nov 25 '12 at 22:10

1 Answers1

5

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.

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309