search
HomeWeb Front-endJS TutorialApplication of Immutable in JavaScript_javascript skills

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 吗?

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

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 的作用一样

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);

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'

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'});

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'

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
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
JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

See all articles

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

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment