If a string is immutable, does that mean that.... (let\'s assume JavaScript)
var str = \'foo\';
alert(str.substr(1)); // oo
alert(str); // foo
On a lower level, immutability means that the memory the string is stored in will not be modified. Once you create a string "foo"
, some memory is allocated to store the value "foo"
. This memory will not be altered. If you modify the string with, say, substr(1)
, a new string is created and a different part of memory is allocated which will store "oo"
. Now you have two strings in memory, "foo"
and "oo"
. Even if you're not going to use "foo"
anymore, it'll stick around until it's garbage collected.
One reason why string operations are comparatively expensive.