Skip to content

Mutable vs. Immutable / StringBuilder vs. String

July 14, 2009
tags: , , ,

So, strings are immutable. What this means in application is that modifying a string creates new string data on the heap and modifies the pointer on the stack to point to the new location. The data on the heap that is not referenced from the stack will be cleared at garbage collection time, but until then it’s wasteful.

In comparison, StringBuilders are mutable. Modifications/additions to the stringbuilder will update the data in the heap instead of making copies of it each time.

StringBuilder sb = new StringBuilder;


sb.Add(” and test2″);

That code will create a pointer on the stack and a data value on the heap, update that data value to add the second string and that’s it. Doing the same with strings would have left an abandoned string data value on the heap of value “test” waiting on the GC.

5 Comments leave one →
  1. Hemanth V permalink
    July 29, 2011 4:51 am

    Nice Example .Thanks

  2. vamsi permalink
    May 3, 2012 7:28 am


  3. NaveenReddy Bommu permalink
    April 2, 2013 7:38 am

    very nice.

  4. June 21, 2013 12:37 pm

    grt explanation…thanks

  5. SHA permalink
    August 19, 2013 4:55 pm

    Very simple and straightforward with a good example.


Leave a Reply

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

You are commenting using your 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

%d bloggers like this: