What is the best way to add two strings together?

Posted by Pim Jager on Stack Overflow See other posts from Stack Overflow or by Pim Jager
Published on 2009-03-29T18:44:24Z Indexed on 2010/06/11 20:12 UTC
Read the original article Hit count: 155

Filed under:
|
|

I read somewehere (I thought on codinghorror) that it is bad practice to add strings together as if they are numbers, since like numbers, strings cannot be changed. Thus, adding them together creates a new string. So, I was wondering, what is the best way to add two strings together, when focusing on performance?

Which of these four is better, or is there another way which is better?

//Note that normally at least one of these two strings is variable
$str1 = 'Hello ';
$str2 = 'World!'; 
$output1 = $str1.$str2; //This is said to be bad

$str1 = 'Hello ';
$output2 = $str1.'World!'; //Also bad

$str1 = 'Hello';
$str2 = 'World!';
$output3 = sprintf('%s %s', $str1, $str2); //Good?
//This last one is probaply more common as:
//$output = sprintf('%s %s', 'Hello', 'World!');

$str1 = 'Hello ';
$str2 = '{a}World!';
$output4 = str_replace('{a}', $str1, $str2);

Does it even matter?

© Stack Overflow or respective owner

Related posts about php

Related posts about Performance