Reputation: 1430
As the title suggests, is there any reason I shouldn't do the following to append something on to the end of a string:
string someString = "test";
someString += "Test";
Upvotes: 2
Views: 290
Reputation: 39990
If you do the following:
var s = "abc";
s += "def";
s += "ghi";
what (more-or-less) happens is that on line 2, as the new string is being created, the contents of abc
are copied into it, then the content of def
is copied into it, then this new string (abcdef
) is assigned to the variable.
Then on line 3, another new string is created, the contents of the previous value of the variable (abcdef
) are copied into it, then ghi
, then the result is assigned to the variable.
If you do this repeatedly, you can see that the beginning of the string is being copied again and again on every +=
operation. In a loop that builds up a long string this could make an impact. This can be optimised by using a StringBuilder
or a List<string>
with string.Concat()
, so that you only ever copy every part of the final result once (or some other constant number independent of the number of loop iterations).
Upvotes: 4
Reputation: 1027
Your approach will work fine. You could use a StringBuilder as an alternative.
var sb = new StringBuilder();
sb.Append("Foo");
sb.Append(" - ");
sb.Append("Bar");
string someString = sb.ToString();
Upvotes: 0
Reputation: 8469
If done once, it's no big deal. The content of the two strings is taken, a new string is created and assigned to someString
. If you do the above operation many times (for example, in a loop), then there is a problem. For each execution, you're allocating a new object in the heap, a new string instance. That's why it's better to use a buffer-based type, such as StringBuilder
, if you have to append content to a string multiple times.
Upvotes: 7