views:

986

answers:

9

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?

+6  A: 

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.

Ed Swangren
+2  A: 

As the others said, $str1 . $str2 is perfectly OK in most cases, except in (big) loops.
Note that you overlook some solutions:

$output = "$str1$str2";

and for large number of strings, you can put them in an array, and use implode() to get a string out of them.

Oh, and "adding strings" sounds bad, or at least ambiguous. In most languages, we prefer to speak of string concatenation.

PhiLho
Ah ok, I'm not a native english speaker so I knew it was something like that word, but I kept thinking concentating (which is a completely different word (is it even a word?))
Pim Jager
+5  A: 

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.

Patrick Daryll Glandien
A: 

The advice you have read may have been related to the echo function, for which it's quicker to use commas, eg:

echo $str1, $str2;

Another approach is to build up a string in a variable (eg using the . operator) then echo the whole string at the end.

You could test this yourself using the microtime function (you'll need to make a loop that repeats eg 1,000 or 100,000 times to make the numbers significant). But of the four you posted, the first one is likely to be the fastest. It's also the most readable - the others don't really make sense programmatically.

DisgruntledGoat
+1  A: 

I can't necessarily speak for PHP, but other languages such as Java or C# you will find that strings are immutable. This means it has to create an entirely new object instead of 'changing' the current string. Generally you'd want to use a StringBuilder (or StringBuffer for older versions) which will keep track of the strings internally instead of creating a single new string. This can help speed it up a little bit. One thing to note is that when you create strings like this:

mystring = "lalala" + "hehehe" + "wakawaka";

then the compiler will just concatenate them before run time anyway so you don't need to worry about it.

For PHP, as far as I know, the only big performance thing you can do for yourself would be to use single quotes instead of double quotes where it is applicable. You are allowed to use variables within double quotes so those strings always have to be parsed whereas single quoted strings do not.

Joe Philllips
I don't know much about the internals of PHP, but I'm assuming that if I write "hehehe" the compiler will recognize that this doesn't need to be parsed, and not parse it at runtime.
Zifre
How does the compiler know it doesn't have to be parsed without examining it? It won't bother to examine single quoted strings.
Joe Philllips
+3  A: 

Unless its really large amount of text it really doesnt matter.

Toby Allen
A: 

This is not a solution for 2 strings, but when you thinking of joining more strings best way like that:

$tmp=srray();
for(;;) $tmp[]='some string';
$str=implode('',$tmp);

It's faster to create array element and join them all at once, than join them hundred times.

Thinker
http://www.php.net/manual/en/language.operators.string.php#48215
Jotham
I have to admit with you. It was faster, but in JS, not PHP, and still it depends on the browser.
Thinker
This is a PHP question. Not a JS question.
Jotham
+2  A: 

It doesn't matter unless used in a looong loop. In usual cases focus on code readability, even if you lost several processor cycles.

Example 1 and 2 are similar, I don't think there should be much difference, this would be the fastes of all. No. 1 might be slightly faster.

Example 3 will be slower, as sprintf format ('%s %s') needs to be parsed.

Example 4 does the replace, which involves searching within a string - additional thing to do, takes more time.

But firstly, is concatenating strings a performance problem? It's very unlikely, you should profile code to measure how much time does it take to run it. Then, replace the concatenating method with a different one and time again.

If you identify it as a problem, try googling for php string builder class (there are some to be found) or write your own.

ya23
A: 

I'm not a PHP guru, however, in many other languages (e.g. Python), the fastest way to build a long string out of many smaller strings is to append the strings you want to concatenate to a list, and then to join them using a built-in join method. For example:

$result = array();
array_push("Hello,");
array_push("my");
array_push("name");
array_push("is");
array_push("John");
array_push("Doe.");
$my_string = join(" ", $result);

If you are building a huge string in a tight loop, the fastest way to do it is by appending to the array and then joining the array at the end.

Note: This entire discussion hinges on the performance of an array_push. You need to be appending your strings to a list in order for this to be effective on very large strings. Because of my limited exposure to php, I'm not sure if such a structure is available or whether php's array is fast at appending new elements.

shadanan
http://www.php.net/manual/en/language.operators.string.php#48215
Jotham