0

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 ?

3
  • 7
    The first will be compiled down to a single string, so the second example is the only one that will actually result in run-time concatenation. Commented May 8, 2013 at 2:55
  • 2
    Does it really matter? ;) codinghorror.com/blog/2009/01/… Commented May 8, 2013 at 3:58
  • I could to choose .Format() or StringBuilder according to context. The dana's links have very good examples. And as there has mentioned,you will see me never using + operator on strings. Commented May 8, 2013 at 4:26

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.