.NET

Difference between String and StringBuilder

Strings are Immutable means whenever you change any value of string variable, a new object is created in memory. That’s why where a significant number of strings modifications need to be done, StringBuilder should be used. Its present in System.TextBuilder namespace.

Now questions comes, why strings are Immutable or what are the benefits of immutability :

  • First, All Immutable instances are thread safe. Because on modifying their values, a new instance is created , So no Thread can actually modify it.
  • There will be no side-effect on passing an immutable types as parameter in a function, as if there is x = “abc” in the starting of function,  that doesn’t change in the body of the method, then x == "abc" at the end of the method.
  • Copying is fast and simple, to create a clone just return this. Since the copy can’t be changed anyway, pretending something is its own copy is safe.
  • You can use strings in Hash-table, key-value pairs collection for their key part.

Categories: .NET, All, c#, Interview

Tagged as: , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.