What's the advantage of a String being Immutable?
Asked Answered
H

7

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.

Heinrich answered 4/8, 2010 at 15:59 Comment(1)
possible duplicate of 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.Enzyme
P
33

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).

Puritan answered 4/8, 2010 at 16:13 Comment(5)
But if you use a 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.Vitric
Several of those arguments seem to be confusing "const" parameters (same as Java "final") with immutability of the referred objects.Trabue
@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.Marrakech
@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.Marrakech
@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)Romaineromains
D
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.

Drongo answered 4/8, 2010 at 16:9 Comment(0)
S
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.

Substation answered 4/8, 2010 at 16:5 Comment(0)
D
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
Durban answered 10/11, 2012 at 14:34 Comment(0)
A
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.

Aalii answered 12/2, 2012 at 18:51 Comment(0)
B
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.

Beery answered 12/4, 2012 at 19:28 Comment(0)
R
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.

Romaineromains answered 27/4, 2014 at 21:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.