Why is it that they decided to make String
immutable in Java and .NET (and some other languages)? Why didn\'t they make it mutable?
It's a trade off. String
s go into the String
pool and when you create multiple identical String
s they share the same memory. The designers figured this memory saving technique would work well for the common case, since programs tend to grind over the same strings a lot.
The downside is that concatenations make a lot of extra String
s that are only transitional and just become garbage, actually harming memory performance. You have StringBuffer
and StringBuilder
(in Java, StringBuilder
is also in .NET) to use to preserve memory in these cases.