Skip to content

RE: Strings are immutable

Sahil has a good post that explains why you should use StringBuilder to concatenate strings instead of just doing “string a” + “string b”

So lets see now, look at this code below —

String

str = “Sahil ” + “is” + ” a” + ” modern” + ” man”;

So right in the code above, how many times did the memory get allocated, and then de-allocated? Dude in the above code, first the framework will declare memory for all 5 strings, and as you concatenate them, it will have to reallocate, and copy memory all over, and over, and over and over again until it gets the final “str”. This is why, you should use StringBuilder – because that is not an immutable object. It has the ability to reuse the same memory.

Now this has other implications too, but as long as you remember to say “Strings are immutable” and sufficiently explain what you meant by that, your interviewer will be more or less happy.

 

[Via Sahil Malik [MVP C#]]