What does immutable mean?

后端 未结 9 721
借酒劲吻你
借酒劲吻你 2020-11-29 16:07

If a string is immutable, does that mean that.... (let\'s assume JavaScript)

var str = \'foo\';

alert(str.substr(1)); // oo

alert(str); // foo
9条回答
  •  离开以前
    2020-11-29 16:44

    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.

提交回复
热议问题