In JavaScript, all columns, numbers, Boolean, null, and undefined are immutable objects. Arrays, Object, and function are mutable objects.
In simple terms, immutable objects have their own pointer to each value.
Such as:
var a=1
var b=1
a==1 // output:true
var a={x:1}
var b={x:1}
a===b // output:false
a.x===b.x // output:true
Copy the code
When an immutable object is reassigned, the original value and the pointer to the original value still exist, memory-wise. The newly assigned value creates a new pointer and the corresponding value, and then assigns the new pointer to the object.
Var a=1 var obj={b:a} var obj={b:a} var obj={b:a} var obj={b:a} So pointer changes inside OBj are also reflected in newObjCopy the code
As you can see above, when you want to copy a list or Object, if you want the new list not to be affected by the previous list, you should loop over immutable objects in the list.
Advantages of immutable objects: Because a value has only one pointer, reuse saves memory. There is no risk of being overwritten.
Many libraries now make objects and lists immutable to avoid the risk of copying objects and enjoy the advantages described above.
Disadvantages of immutable objects: Large amounts of unused memory can be generated in loops.
Rare cases, such as the following example:
String str="test" for(int i=0; i<100000L; I++){s+="test" // generates 100000L of useless memory}Copy the code
Workaround: Using mutable Objects (In Java, StringBuilder; Ts can use uppercase String.
P.S. Regarding TypeScript, although strings, numbers, and Boolean are mutable objects, the official documentation has advised against using them. So it’s not recommended unless it’s absolutely necessary.
P.S. In addition, Java has StringBuffer and StringBuilder. The former has thread locks and is safer to use with multiple threads, but not as efficient as the latter