The application of immutable in JavaScript _javascript skills

Source: Internet
Author: User
Tags assert data structures

mutable objects
In JavaScript, an object is a reference type of data, the advantage is that the frequent modification of objects are based on the original object, do not need to re-create, so that the efficient use of memory, does not cause the waste of memory space, the object of this feature can be called mutable, The literal meaning of Chinese is "changeable".
For mutable object, its flexible and changeable advantages can sometimes become its disadvantage, the more flexible data is more difficult to control, for a complex structure of the object, accidentally inadvertently modified the data, if the object is used in multiple scopes, It is difficult to foresee whether the data has changed and when.

var obj = {/* object of a complex structure/};
DoSomething (obj);
When the above function is finished, is obj still the original obj at this time?

For this kind of problem, the conventional solution can copy a new object in the form of deep copy of the object, and then modify the operation on the new object, so as to ensure the controllability of the data, but frequent replication can cause a large amount of wasted memory space.

var obj = {/* object of a complex structure/};
Copy out a new obj2
//But the copy operation will waste memory space
var obj2 = deepclone (obj);
DoSomething (OBJ2);
After the completion of the function above, regardless of whether the obj2 changes, obj must still be the original obj.

Immutable Object
in order to better solve the above problems, there are immutable objects, immutable literally translated into Chinese is "immutable." A new immutable object is created each time a immutable object is modified, and the action on the new object does not affect the original object's data. This particular object is not a new feature of JavaScript, but a set of solutions offered by the industry to address this problem, and the emergence of some excellent open-source libraries, most notably Facebook's Lee Byron open source immutable.js. Of course, immutable's solution is not original, but comes from Clojure and Scala.
Comparison of performance between mutable and immutable
The inefficient operation of mutable objects is mainly reflected in replication and comparison, and the immutable object is to solve these two inefficient pain points.
A deep copy of a normal mutable object copies an entire piece of data, the immutable object, while modifying the data, does not copy an entire piece of data, but instead shifts the changed node to a new node, similar to the structure of the linked list, with the unchanged node's parent-child relationship. From the "Copy" point of view, do a minimum of replication, unchanged parts are shared, mutable in the copy is "full volume", and immutable copy is "increment" for the memory space usage rate of the comparison of the high and low.
and it is convenient to save the modified state of the data as a set of snapshots, based on the feature that creates a new immutable object with each immutable object modified.
again, compare operations. For mutable objects, if you want to compare two objects for equality, you must iterate through each node of the object to compare, and for complex objects, the efficiency is certainly not high. For immutable objects, Immutable.js provides an API that directly determines whether the value of two immutable objects is equal.

var map1 = Immutable.map ({a:1, b:1, c:1});
var map2 = Immutable.map ({a:1, b:1, c:1});
ASSERT (Map1!== map2); Different immutable instances, at which point the reference address
assert (immutable.is (MAP1, MAP2)) is compared;//MAP1 and MAP2 have equal values, compared to the value
assert (Map1.equals ( MAP2)); The same as immutable.is.

In practical development applications, performance is not always the most critical and important, for ordinary JavaScript projects, due to the immutable characteristics of the data is more controllable than the performance of the advantages, for the Mutable object is suitable for the closed scope of the use of a small, and The immutable object is suitable for use when data needs to be passed across multiple scopes.

The difference between mutable and immutable in use

Immutable.js provides a variety of immutable data structures: Contains the List Stack Map orderedmap Set orderedset record, which corresponds roughly to the native mutable data structure.
The usage of the data structure here does not elaborate, basically say immutable object and mutable object in use of difference.
Native mutable objects are very handy for "read" and "write".

var mutableobj = {};
Write data
Mutableobj.foo = ' bar ';
Read Data
console.log (Mutableobj.foo);

The immutable object needs to "read" and "write" the 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 '

The example above, in order to illustrate the use of the Set method, creates an empty object at the beginning, and can actually pass the initial value when instantiated.

var immutableobj = immutable.map ({' foo ', ' Bar '});

For deeper-level data, Immutable.js provides a convenient access interface.

var immutableObj1 = Immutable.fromjs ({
 A: {
  B: ' C '
 },
 D: [1, 2, 3]
});
Read the deep level data
Console.log (Immutableobj1.getin ([' A ', ' B ']));//=> ' C '
console.log (Immutableobj1.getin ([' d ', 1])); => 2
//Modify 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 object undefined error may be reported when a chained access to a deep level of data is encountered, and the immutable object does not complain when encountering this situation, and returns undefined.
When debugging, if you want to see the internal structure of a immutable object, it is recommended that you use Tojson () to convert to a normal mutable object first.

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.