Are JavaScript strings immutable? Do I need a “string builder” in JavaScript?

后端 未结 10 2656
挽巷
挽巷 2020-11-22 02:48

Does javascript use immutable or mutable strings? Do I need a \"string builder\"?

10条回答
  •  情书的邮戳
    2020-11-22 03:50

    Just to clarify for simple minds like mine (from MDN):

    Immutables are the objects whose state cannot be changed once the object is created.

    String and Numbers are Immutable.

    Immutable means that:

    You can make a variable name point to a new value, but the previous value is still held in memory. Hence the need for garbage collection.

    var immutableString = "Hello";

    // In the above code, a new object with string value is created.

    immutableString = immutableString + "World";

    // We are now appending "World" to the existing value.

    This looks like we're mutating the string 'immutableString', but we're not. Instead:

    On appending the "immutableString" with a string value, following events occur:

    1. Existing value of "immutableString" is retrieved
    2. "World" is appended to the existing value of "immutableString"
    3. The resultant value is then allocated to a new block of memory
    4. "immutableString" object now points to the newly created memory space
    5. Previously created memory space is now available for garbage collection.

提交回复
热议问题