Reputation: 11464
Is this two patterns of String Concatenation consume same amount of memory?
//Method 1
String testString = "Test " + " string " + " content";
//Method 2
String testString = "Test ";
testString = testString + " string ";
testString = testString + " content";
Should we avoid both of these methods and use StringBuilder
class ?
Upvotes: 0
Views: 3332
Reputation: 91
In my opinion,it is a big difference between these two method. After building,in method 1,string testString = "Test string content", but in method 2,string testString = "Test ", in run-time,they are also different,in method 1,string testString just refrence to an address in immutable,but in method 2,the clr allocate the new memory in heap and combine the strings together. And i think StringBuilder is a good way for combining string frequently.
Upvotes: 0
Reputation: 151
Method 2 would result in more allocation of memory, string object shall be created to store the following combinations
1) "Test "
2) " String"
3) "Test string"
4) " Content"
5) "Test String Content"
Where in case of Method 1 just one string shall be created
1) "Test string Content"
Method 1 is should be preferred among these two methods
StringBuilder
class is more efficient when you need to build a string that involves combining many string values.
Upvotes: 2
Reputation: 39248
Yes, StringBuilder is the better option. In all the other cases you describe you are creating multiple new strings since strings are immutable in C# and can't be changed. This causes c# to simulate changes to strings by creating new strings.
Method one could be converted to a single string. There is no need to concatenate fixed substrings to build the string
Upvotes: 2