SharePointAds TextOnly

Friday, 7 August 2009

.Net: Difference between String and Stringbuilder?

Usually, String is immutable type which means once you have the content there then you can't change it. While StringBuilder is mutable because it allows you to change the content that you have already placed.
Important to keep in mind that a string allows you to change the content but offcourse it always creates a new string reference. For example, all string methods return a new string and don't update the same string variable.
When you have huge amount of concatenation, best recommendation to go for StringBuilder!
String and StringBuilder class stores strings. But when you cannot change a String object after creating one.
eg: String name = "Test";
By saying you can't change the name object means you can't change the value in name object internally. When you change the name object value to something else, a new String object is creating in memory and assign the new value.

eg: name = "Test Example";

A new name object is creating in memory and the value "Test Example" is assinging to the newly created space.

But StringBuilder class occupies the same space even if you change the value.
If you are doing string concatenation StringBuilder class is far better in performance than String class.

You can use StringBuilder's Append() method to use concatenation.

also check this link Example

No comments:

Post a Comment