Home Web Front-end JS Tutorial Application of Immutable in JavaScript_javascript skills

Application of Immutable in JavaScript_javascript skills

May 16, 2016 pm 03:02 PM
Immutable

Mutable object
In JavaScript, objects are reference type data. The advantage is that when objects are frequently modified, they are modified on the basis of the original object and do not need to be recreated. This can effectively utilize memory and will not cause a waste of memory space. Objects This feature can be called Mutable, which literally means "variable" in Chinese.
For Mutable objects, their advantages of being flexible and changeable may sometimes become their disadvantages. The more flexible and changeable the data, the harder it is to control. For an object with a complex structure, it may be modified inadvertently. Without data, if the object is used in multiple scopes, it is difficult to predict whether and when the data will change.

var obj = { /* 一个复杂结构的对象 */ };
doSomething(obj);
// 上面的函数之行完后,此时的 obj 还是最初的那个 obj 吗?
Copy after login

To address this problem, the conventional solution is to copy the object into a new object in the form of a deep copy, and then perform modification operations on the new object. This can ensure the controllability of the data, but frequent Copying can cause a lot of waste of memory space.

var obj = { /* 一个复杂结构的对象 */ };
// copy 出一个新的 obj2
// 但是 copy 操作会浪费内存空间
var obj2 = deepClone(obj);
doSomething(obj2);
// 上面的函数之行完后,无论 obj2 是否变化,obj 肯定还是原来那个 obj
Copy after login

Immutable object
In order to better solve the above problems, the Immutable object appeared. Immutable literally translates into Chinese as "immutable". Every time an Immutable object is modified, a new immutable object is created, and operations on the new object will not affect the data of the original object. This special object is not a new feature of JavaScript, but a set of solutions provided by the industry to solve this problem, and some excellent open source libraries have emerged, the most famous of which is Facebook's Lee Byron open source immutable.js. Of course, Immutable's solution is not original, but comes from Clojure and Scala.
Performance comparison between Mutable and Immutable
The inefficient operations on Mutable objects are mainly reflected in copying and comparison, and Immutable objects solve these two inefficient pain points.
The deep copy operation of an ordinary Mutable object will copy the entire data, but the Immutable object will not copy the entire data when modifying the data, but will transfer the parent-child relationship between the changed node and the unchanged node to On a new node, a structure similar to a linked list. From the perspective of "copy", minimal copying is achieved, and the unchanged parts are shared. Mutable copies "full amount", while Immutable copies "increment", and the usage of memory space is Judgment will be made based on the comparison of the rates.
And based on the feature that a new Immutable object is created every time an Immutable object is modified, the modification status of the data can be saved as a set of snapshots, which is also very convenient.
Let’s talk about comparison operations. For Mutable objects, if you want to compare whether two objects are equal, you must traverse each node of the object for comparison. For objects with complex structures, the efficiency is definitely not much higher. 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); // 不同的 Immutable 实例,此时比较的是引用地址
assert(Immutable.is(map1, map2)); // map1 和 map2 的值相等,比较的是值
assert(map1.equals(map2)); // 与 Immutable.is 的作用一样
Copy after login

In actual development applications, performance is not always the most critical and important. For ordinary JavaScript projects, the controllability of data brought by the characteristics of Immutable is more advantageous than performance. , Mutable objects are suitable for use in a small range of closed scopes, while Immutable objects are suitable for use when data needs to be passed across multiple scopes.

The difference in usage between Mutable and Immutable

immutable.js provides a variety of Immutable data structures: including List Stack Map OrderedMap Set OrderedSet Record. These data structures roughly correspond to the native Mutable data structures.
The usage of each data structure will not be explained in detail here. Let’s mainly talk about the difference in usage between Immutable objects and Mutable objects.
Native Mutable objects are very convenient for "reading" and "writing".

var mutableObj = {};
// 写入数据
mutableObj.foo = 'bar';
// 读取数据
console.log(mutableObj.foo);
Copy after login

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

var immutableObj1 = Immutable.Map();
// 写入数据
var immutableObj2 = immutableObj1.set('foo', 'bar');
// 读取数据
console.log(immutableObj2.get('foo')); // => 'bar'
Copy after login

The above example only creates an empty object at the beginning to illustrate the use of the set method. In fact, the initial value can be passed during instantiation.

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

For deep-level data, the access interface provided by immutable.js is very convenient.

var immutableObj1 = Immutable.fromJS({
 a: {
  b: 'c'
 },
 d: [1, 2, 3]
});
// 读取深层级的数据
console.log(immutableObj1.getIn(['a', 'b'])); // => 'c'
console.log(immutableObj1.getIn(['d', 1])); // => 2
// 修改深层级的数据
var immutableObj2 = immutableObj1.setIn(['a', 'b'], 'd');
console.log(immutableObj2.getIn(['a', 'b'])); // => 'd'
Copy after login

If it is a native Mutable object, an object undefined error may be reported when chaining access to a deep-level data. However, the Immutable object will not report an error when encountering this situation and returns undefined.
When debugging, if you want to view the internal structure of an Immutable object, it is recommended to use toJSON() to convert it to an ordinary Mutable object first.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

ImmutableX (IMX) Price Analysis: Bulls Aim to Flip $1.53 Resistance Zone into Support ImmutableX (IMX) Price Analysis: Bulls Aim to Flip $1.53 Resistance Zone into Support Aug 30, 2024 am 09:16 AM

IMX was trading at a key resistance zone that was both a Fibonacci retracement level and a bearish order block. The Bitcoin (BTC) price plunge from $64.2k to $58.2k saw IMX prices drop by 13%.

Immutable Shuts Down NFT Marketplace, Kanpai Pandas NFTs Plunge Amid Trump Token Controversy Immutable Shuts Down NFT Marketplace, Kanpai Pandas NFTs Plunge Amid Trump Token Controversy Aug 15, 2024 am 06:31 AM

In this week's newsletter, find out why Immutable has retired its non-fungible token (NFT) marketplaces and why Kanpai Pandas NFTs floor prices dropped after the team's involvement in a Donald Trump-themed token. Check out why an executive believes W

Immutable (IMX) Price Swings Ahead of Token Unlock Events Immutable (IMX) Price Swings Ahead of Token Unlock Events Oct 01, 2024 pm 10:24 PM

IMX price, a layer-two scaling solution for Ethereum, has shown a bullish trend over the past month, gaining 31%. Despite this increase, the price of IMX is now showing signs of volatility due to a recent market correction.

Blockchain Gaming Platform Immutable Targeted by SEC, IMX Token Price Drops Blockchain Gaming Platform Immutable Targeted by SEC, IMX Token Price Drops Nov 01, 2024 pm 06:18 PM

The United States Securities and Exchange has targeted blockchain gaming platform Immutable potentially targeting its listing and private sales of the IMX token in 2021.

Next Cryptocurrency To Explode: 5 Altcoins To Watch In The Coming Weeks Next Cryptocurrency To Explode: 5 Altcoins To Watch In The Coming Weeks Aug 28, 2024 am 12:21 AM

The altcoin market is fluctuating, but some coins try to bounce back. Investors need to stay alert during this consolidation phase, as it could be a chance to ride a rising trend.

Immutable Shuts Down Its NFT Marketplace to Focus on Ecosystem Expansion Immutable Shuts Down Its NFT Marketplace to Focus on Ecosystem Expansion Aug 09, 2024 am 12:12 AM

Immutable, a prominent layer-2 network in the blockchain gaming and non-fungible token (NFT) space, has announced the closure of its NFT marketplace.

Immutable Receives Wells Notice From SEC, Signaling Potential Enforcement Action Immutable Receives Wells Notice From SEC, Signaling Potential Enforcement Action Nov 01, 2024 pm 03:30 PM

Blockchain gaming platform, Immutable, received a Wells notice from the U.S. Securities and Exchange Commission (SEC), signaling potential enforcement action for alleged securities violations.

Immutable Labs Challenges SEC Wells Notice, Advocates for Clear Crypto Regulation Immutable Labs Challenges SEC Wells Notice, Advocates for Clear Crypto Regulation Nov 07, 2024 am 09:18 AM

Immutable has stated its intention to challenge the SEC's claims, which it believes focus on the listing and private sales of its native IMX token in 2021.

See all articles