21

Once I studied about the advantage of a string being immutable because of something to improve performace in memory.

Can anybody explain this to me? I can't find it on the Internet.

Lipis
  • 21,388
  • 20
  • 94
  • 121
Alan
  • 211
  • 1
  • 2
  • 3
  • 1
    possible duplicate of [What is meant by immutable?](http://stackoverflow.com/questions/279507/what-is-meant-by-immutable). While the title of that question isn't the same, it includes a question about advantages and disadvantages, which at least one of the answers (by Imagist) covers quite well. – Jerry Coffin Aug 04 '10 at 16:03

7 Answers7

34

Immutability (for strings or other types) can have numerous advantages:

  • It makes it easier to reason about the code, since you can make assumptions about variables and arguments that you can't otherwise make.
  • It simplifies multithreaded programming since reading from a type that cannot change is always safe to do concurrently.
  • It allows for a reduction of memory usage by allowing identical values to be combined together and referenced from multiple locations. Both Java and C# perform string interning to reduce the memory cost of literal strings embedded in code.
  • It simplifies the design and implementation of certain algorithms (such as those employing backtracking or value-space partitioning) because previously computed state can be reused later.
  • Immutability is a foundational principle in many functional programming languages - it allows code to be viewed as a series of transformations from one representation to another, rather than a sequence of mutations.

Immutable strings also help avoid the temptation of using strings as buffers. Many defects in C/C++ programs relate to buffer overrun problems resulting from using naked character arrays to compose or modify string values. Treating strings as a mutable types encourages using types better suited for buffer manipulation (see StringBuilder in .NET or Java).

LBushkin
  • 129,300
  • 32
  • 216
  • 265
  • 1
    But if you use a [Copy-On-Write](http://en.wikipedia.org/wiki/Copy-on-write) paradigm, you have the advantages of immutable strings *and* private copies and in-place modification, if needed, e.g. for fast parsing. `StringBuilder` is just a workaround to slow immutable string concatenation, and of little benefit in respect to the COW pattern associated with a efficient heap-management system. COW can allow your buffer access to be safe *and* fast at the same time. – Arnaud Bouchez May 11 '13 at 10:00
  • Several of those arguments seem to be confusing "const" parameters (same as Java "final") with immutability of the referred objects. – Eric Grange May 11 '13 at 13:50
  • @LBushkin, Although you make some good arguments in your bullet points, your "Immutable strings also help avoid..." paragraph is a misleading. StringBuilder solves absolutely different problem than buffer overriding in C - it's just optimization for string concatenation, because concatenating immutable strings is slow - you need to create two new objects and copy all characters for every concatenation step. – Alexey Dec 04 '13 at 22:00
  • @ArnaudBouchez, COW does not have ALL advantages of immutable objects, it just provides some performance gains for majority of cases for strings. However, "It makes it easier to reason about the code" - this advantage of immutable objects is not provided by COW pattern. – Alexey Dec 04 '13 at 22:08
  • @Alexey: Copy-on-write could be helpful in languages where one could specify that variables `s1` an `s2` of type `String` should each hold the only reference anywhere in the universe to a separate instance of `StringRef`, and that `s1=s2;` should be performed as `s1.CopyFrom(s2);`, without changing which instance of `StringRef` `s1` refers to. Java and .NET languages don't support such a concept, but C++ does (at least in code that doesn't have to interact with other .NET languages) – supercat May 09 '14 at 18:46
9

Consider the alternative. Java has no const qualifier. If String objects were mutable, then any method to which you pass a reference to a string could have the side-effect of modifying the string. Immutable strings eliminate the need for defensive copies, and reduce the risk of program error.

Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
5

Immutable strings are cheap to copy, because you don't need to copy all the data - just copy a reference or pointer to the data.

Immutable classes of any kind are easier to work with in multiple threads, the only synchronization needed is for destruction.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
1

Perhaps, my answer is outdated, but probably someone will found here a new information.

Why Java String is immutable and why it is good:

  • you can share a string between threads and be sure no one of them will change the string and confuse another thread
  • you don’t need a lock. Several threads can work with immutable string without conflicts
  • if you just received a string, you can be sure no one will change its value after that
  • you can have many string duplicates – they will be pointed to a single instance, to just one copy. This saves computer memory (RAM)
  • you can do substring without copying, – by creating a pointer to an existing string’s element. This is why Java substring operation implementation is so fast
  • immutable strings (objects) are much better suited to use them as key in hash-tables
fycth
  • 3,410
  • 25
  • 37
0

a) Imagine StringPool facility without making string immutable , its not possible at all because in case of string pool one string object/literal e.g. "Test" has referenced by many reference variables , so if any one of them change the value others will be automatically gets affected i.e. lets say String A = "Test" and String B = "Test" Now String B called "Test".toUpperCase() which change the same object into "TEST" , so A will also be "TEST" which is not desirable.
b) Another reason of Why String is immutable in Java is to allow String to cache its hashcode , being immutable String in Java caches its hash code and do not calculate every time we call hashcode method of String, which makes it very fast as hashmap key.

Anand
  • 20,708
  • 48
  • 131
  • 198
0

Fundamentally, if one object or method wishes to pass information to another, there are a few ways it can do it:

  1. It may give a reference to a mutable object which contains the information, and which the recipient promises never to modify.

  2. It may give a reference to an object which contains the data, but whose content it doesn't care about.

  3. It may store the information into a mutable object the intended data recipient knows about (generally one supplied by that data recipient).

  4. It may return a reference to an immutable object containing the information.

Of these methods, #4 is by far the easiest. In many cases, mutable objects are easier to work with than immutable ones, but there's no easy way to share with "untrusted" code the information that's in a mutable object without having to first copy the information to something else. By contrast, information held in an immutable object to which one holds a reference may easily be shared by simply sharing a copy of that reference.

supercat
  • 77,689
  • 9
  • 166
  • 211
0

Think of various strings sitting on a common pool. String variables then point to locations in the pool. If u copy a string variable, both the original and the copy shares the same characters. These efficiency of sharing outweighs the inefficiency of string editing by extracting substrings and concatenating.

greeness
  • 15,956
  • 5
  • 50
  • 80