Sub topic 5
Why many languages make strings immutable
This chapter assumes you know what indexing and slicing do on a string, and that you can read basic Big-O notation. You should also know that a variable refers to a value stored in memory.
What immutable means
An immutable string cannot be changed after it is created. Operations that look like edits, such as replacing a character or converting to uppercase, build a new string and leave the original alone.
s = "hello"
print(s[1]) # e
print(s[-1]) # o
print(s[1:4]) # ell
try:
s[0] = "J"
except TypeError:
print("strings are immutable")
t = "J" + s[1:]
print(t) # JelloReading with an index or a slice works. Assigning to an index raises TypeError. To get a changed string, you build a new one. Here t is a new string, and s still holds "hello".
A common mistake: expecting methods to edit in place
Because string methods return new strings, ignoring the return value does nothing.
name = "ada"
name.upper() # result is thrown away
print(name) # ada
name = name.upper() # rebind the name to the new string
print(name) # ADAThe second assignment does not modify the old string. It points the name name at a new string object.
Why language designers choose this
Immutability gives several guarantees, and each one makes other parts of the language simpler.
- Safe sharing. Two variables can refer to the same string without copying it. Nobody can change it behind the other's back.
- Stable hash keys. A dictionary stores a key in a position computed from its hash. If a key could change, its hash would change and the entry would become unreachable. Immutable strings make good keys.
- Interning. The runtime can keep one copy of a common string, such as an identifier, and reuse it. This only works if no holder can modify that copy.
- Thread safety. Several threads can read the same string with no locks, because no thread can write to it.
- Security. A path or user name that passes a validation check cannot be altered before it is used.
The next diagram shows sharing and rebinding.
What it costs
Every "edit" copies data. Changing one character in a string of length n takes O(n) time and O(n) extra memory, because the new string must hold all n characters. Doing this in a loop adds up quickly. The next chapter covers how to avoid that cost.
Immutability also affects the cost of slicing. Some runtimes copy the slice. Others share the original buffer, which is cheap but can keep a large string alive because of a small slice. Check how your language behaves before you slice many small pieces out of a very large string.
Where languages differ
Not every language makes this choice.
| Language | Default string type | Mutable in place? |
|---|---|---|
| Python | `str` | No |
| Java | `String` | No |
| JavaScript | string | No |
| C# | `string` | No |
| Go | `string` | No |
| Rust | `String` | Yes, but `&str` is a read-only view |
| Ruby | `String` | Yes, by default |
| C++ | `std::string` | Yes |
| C | `char` array | Yes |
Languages that allow mutation leave the safety work to you. If you share a mutable string between two parts of a program, you must decide who may change it.
Mutable alternatives when you need them
Immutable languages usually provide a mutable companion for heavy editing. In Python you can use a list of characters, or bytearray for bytes. Java has StringBuilder, and C# has StringBuilder as well.
chars = list("hello")
chars[0] = "J"
print("".join(chars)) # JelloThis copies the string once into a list, edits it, and then copies it back into a string with join. It pays off when you make many edits, because each edit is O(1) instead of O(n).
Key points
- An immutable string never changes. Edits produce new strings.
- The main benefits are safe sharing, stable hashing, interning, and thread safety.
- The main cost is copying, which is O(n) per edit.
- Use a mutable buffer or builder when you make many edits.
Exercise
A program stores user names in a dictionary, and a colleague proposes using a mutable list of characters as the key to make renaming cheap. Explain why this fails in Python, and say what you would do to support renaming.
Show answer
A list is mutable and therefore unhashable, so d[["a"]] = 1 raises TypeError. If a key could change after insertion, its hash would change and the entry could no longer be found. Keep the keys as immutable strings. To rename a user, remove the old key and insert the new string, for example d[new] = d.pop(old).