Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to add two strings together?

Tags:

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?

like image 444
Pim Jager Avatar asked Mar 29 '09 18:03

Pim Jager


2 Answers

String Concatenation with a dot is definitely the fastest one of the three methods. You will always create a new string, whether you like it or not. Most likely the fastest way would be:

$str1 = "Hello"; $str1 .= " World";

Do not put them into double-quotes like $result = "$str1$str2"; as this will generate additional overhead for parsing symbols inside the string.

If you are going to use this just for output with echo, then use the feature of echo that you can pass it multiple parameters, as this will not generate a new string:

$str1 = "Hello"; $str2 = " World"; echo $str1, $str2;

For more information on how PHP treats interpolated strings and string concatenation check out Sarah Goleman's blog.

like image 157
Patrick Glandien Avatar answered Oct 01 '22 18:10

Patrick Glandien


You are always going to create a new string whe concatenating two or more strings together. This is not necessarily 'bad', but it can have performance implications in certain scenarios (like thousands/millions of concatenations in a tight loop). I am not a PHP guy, so I can't give you any advice on the semantics of the different ways of concatenating strings, but for a single string concatenation (or just a few), just make it readable. You are not going to see a performance hit from a low number of them.

like image 40
Ed S. Avatar answered Oct 01 '22 17:10

Ed S.