Immutable in JavaScript _ javascript skills

Source: Internet
Author: User
In JavaScript, objects are data of reference type. The advantage is that objects are modified on the basis of the original object frequently and do not need to be re-created, so that the memory can be effectively used, it will not cause a waste of memory space. This feature of an object can be called Mutable. the literal meaning of a Chinese character is "Mutable 」 Mutable object
In JavaScript, objects are data of reference type. The advantage is that objects are modified on the basis of the original object frequently and do not need to be re-created, so that the memory can be effectively used, it will not cause a waste of memory space. This feature of an object can be called Mutable. the literal meaning of a Chinese character is "Mutable 」.
For Mutable objects, the flexible and changing advantages may sometimes become their disadvantages. The more flexible and changing the data, the less difficult it is to control. For a complex structure object, accidentally modify the data in a certain scope. If the object is used in Multiple scopes, it is difficult to predict whether or not the data is changed and when it is changed.

Var obj = {/* a complex structure object */}; doSomething (obj); // After the preceding function is complete, is the obj the original obj?

To solve this problem, we can copy a new object in the form of a deep copy of the object, and then modify the object, this ensures data controllability, but frequent replication can result in a large waste of memory space.

Var obj = {/* a complex structure object */}; // copy a new obj2 // but the copy operation will waste the memory space var obj2 = deepClone (obj ); doSomething (obj2); // After the above function is complete, no matter whether obj2 changes or not, obj must be the original obj

Immutable object
In order to better solve the above problems, Immutable objects have emerged, and Immutable is literally translated into Chinese as "Immutable 」. Each time you modify an Immutable object, a new Immutable object is created. operations on the new object do not affect the data of the original object. This special object is not a new functional feature of JavaScript, but a set of solutions provided by the industry to solve this problem, and some excellent open-source class libraries have emerged, among them, the most famous is Facebook's Lee Byron open-source immutable. js. Of course, Immutable's solution is not original, but from Clojure and Scala.
Performance Comparison Between Mutable and Immutable
The inefficient operations on Mutable objects are mainly reflected in the replication and comparison, while the Immutable object solves the two pain points of inefficiency.
The deep copy operation of a common Mutable object copies all the data, while the Immutable object does not copy the whole data when modifying the data, instead, it transfers the parent-child relationship between the changed node and the unchanged node to a new node, similar to the linked list structure. From the perspective of "replication", the minimal replication is achieved. The unchanged part is shared, and Mutable is "full" during replication ", immutable replicates "incremental" and determines the memory space usage.
In addition, a new Immutable object is created every time an Immutable object is modified. This feature can save the data modification status as a set of snapshots, which is quite convenient.
Let's talk about the comparison operation. For Mutable objects, to compare whether two objects are equal, each node of the object must be traversed for comparison. For objects with complex structures, the efficiency is definitely not high. For Immutable objects, immutable. js provides an API to directly determine whether the "values" of two Immutable objects are equal.

Var map1 = Immutable. map ({a: 1, B: 1, c: 1}); var map2 = Immutable. map ({a: 1, B: 1, c: 1}); assert (map1! = Map2); // for different Immutable instances, the reference address assert (Immutable. is (map1, map2); // values of map1 and map2 are equal, and assert (map1.equals (map2) values are compared; // and Immutable. is works the same.

In actual development and application, performance is not always the most critical and important. For common JavaScript projects, the controllability of data caused by Immutable features is more advantageous than performance, mutable objects are suitable for a small range of closed scopes, while Immutable objects are suitable for data that needs to be transferred across multiple scopes.

Differences between Mutable and Immutable

Immutable. js provides a variety of Immutable data structures: including List Stack Map OrderedMap Set OrderedSet Record, which roughly correspond to the native Mutable data structure.
The usage of each data structure is not detailed here. It mainly describes the differences between Immutable object and Mutable object.
The native Mutable object is very convenient in "read" and "write.

Var mutableObj ={}; // write data mutableObj. foo = 'bar'; // read data console. log (mutableObj. foo );

The Immutable object needs to read and write data through set and get 」.

Var immutableObj1 = Immutable. map (); // write data var immutableObj2 = immutableObj1.set ('foo', 'bar'); // read data console. log (immutableObj2.get ('foo'); // => 'bar'

In the above example, an empty object is created at the beginning to demonstrate the use of the set method. In fact, the initial value can be passed during instantiation.

var immutableObj = Immutable.Map({'foo', 'bar'});

Immutable. js provides easy access interfaces for hierarchical data.

Var immutableObj1 = Immutable. fromJS ({a: {B: 'C'}, d: [1, 2, 3]}); // read the in-depth data console. log (immutableObj1.getIn (['A', 'B']); // => 'C' console. log (immutableObj1.getIn (['D', 1]); // => 2 // modify the deep-level data var immutableObj2 = immutableObj1.setIn (['A ', 'B'], 'D'); console. log (immutableObj2.getIn (['A', 'B']); // => 'D'

If it is a native Mutable object, the undefined error may be reported when the chain accesses a deep-level data, and the Immutable object will not report an error in this case, and the returned result is undefined.
During debugging, if you want to view the internal structure of an Immutable object, we recommend that you use toJSON () to first convert it to a common Mutable object.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.