Mentions some pros and cons of immutable vs mutable Strings

Technology CommunityCategory: StringsMentions some pros and cons of immutable vs mutable Strings
VietMX Staff asked 3 years ago

Immutability has several advantages, including (but not limited to):

  • Programs with immutable objects are less complicated to think about, since you don’t need to worry about how an object may evolve over time.
  • You don’t need to make defensive copies of immutable objects when returning or passing to other functions, since there is no possibility an immutable object will be modified behind your back.
  • One copy of an object is just as good as another, so you can cache objects or re-use the same object multiple times.
  • Immutable objects are good for sharing information between threads in a multi-threaded environment since they don’t need to be synchronized and no locking shall be performed
  • Operations on immutable objects return new immutable objects while operations that cause side-effects on mutable objects usually return void. This means several operations can be chained together. For instance

("foo" + "bar" + "baz").length()

  • In languages where functions are first class values, operations like mapreducefilter, etc. are basic operations on collections. These can be combined in many ways, and can replace most loops in a program.
  • Runtime safety. In some languages like Java strings are immutable and cannot be subclassed. This means that the Java runtime can pass around and receive strings from the user while guaranteeing that the string’s value will remain constant.

There are of course some disadvantages:

  • Cyclic data structures such as graphs are difficult to build. If you have two objects which can’t be modified after initialization, how can you get them to point to each other?
  • Allocating lots and lots of small objects rather than modifying ones you already have can have a performance impact. Usually the complexity of either the allocator or the garbage collector depends on the number of objects on the heap.
  • Naive implementations of immutable data structures can result in extremely poor performance. For instance, concatenating many immutable strings (like in Java) is O(n<sup>2</sup>) when the best algorithm is O(n). It is possible to write efficient immutable data structures, it just takes a little more thought.