While reviewing Yossi (new teammate) code I've seen something strange, it looks almost like this:
string formatStr;
formatStr = String.Format("Hello {0}",name);
I ask him for explanation and he gave a wonderful story which almost convinces me that this one isn't so bad, it sounds like this:
· This is better than concatenate two immutable strings
· This is more readable.
So I thought for a second and changed the code to look like this:
string concatStr = "Hello " + name;
But he insists that this one is bad, concatenate immutable strings.
So here is my simple explanation:
1. With human-readability I won't argue, it is (sometimes) very individual.
2. My code isn't about concatenating it is about init strings and for that main reason the compiler would change this code to one large string (known at compile time). (You can see the Ildasm).
String.Format implementation remark:
· Be careful, while calling string.Format it creates StringBuilder and do its stuff - do you really want it?
I know that most of you screaming out loud (waaaa.... or just saying: OK and what with 10 or even more concatenation)
you probably wrote script generation which look like this:
public string WriteHtmlMessage()
{
return "<div>" +
"I would like to add <b>" + name + "</b>" +
"<br/>" +
"to my team as a <b>" + job + "</b>" +
"</div>";
}
And yes this is an init statement so it is better (performance reasons) writing it like this then using String.Format or even StringBuilder.
Even if the compiler will use the Concat method it will be used with the array parameter which is still better than creating String.Builder.
Why is it better?
Because the size of the array is known at compile time.
Conclusion,
· The compiler will translate the init concatenation to a long string (like my first example) when all the strings are known at compile time (the parameter was const).
· The compiler will use concat method (with arraylist, not the poor pairs concat) when the number of strings are known at compile time (last example).
In both examples this concat is actually faster than StringBuilder or String.Format.
So, next time when you concatenate specific (known) strings do it in the same init instruction.