Why can't strings be mutable in Java and .NET?

后端 未结 17 2006
不思量自难忘°
不思量自难忘° 2020-11-22 14:04

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?

17条回答
  •  无人及你
    2020-11-22 14:41

    It's a trade off. Strings go into the String pool and when you create multiple identical Strings 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 Strings 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.

提交回复
热议问题