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";
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";
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):
Conclusion
Concatenation is faster, though it's unlikely to impact the performance of any particular application.