Home  >  Article  >  Web Front-end  >  Front-end Advanced (1): Memory Space Diagram

Front-end Advanced (1): Memory Space Diagram

PHPz
PHPzOriginal
2017-04-04 17:23:491166browse

Front-end Advanced (1): Memory Space Diagram

VariablesObjectswith heap memory

var a = 20;
var b = 'abc';
var c = true;
var d = { m: 20 }

Because JavaScript has automatic garbage Recycling mechanism, so for front-end development, memory space is not a concept that is often mentioned, and it is easily ignored by everyone. In particular, many friends who are not computer majors have a vague understanding of memory space after entering the front-end, and some even know nothing about it.

Of course including myself. For a long time, I thought that the concept of memory space was not that important in the learning of JS. But later, when I went back and reorganized the basics of JS, I found that due to my vague understanding of them, I did not understand many things. For example, what is going on with the most basic referencedata type and reference passing? For example, what is the difference between shallow copy and deep copy? There are also closures, prototypes, etc.

So later I gradually understood that if I want to have a deeper understanding of JS, I must have a clear understanding of the memory space.

1. Stack and Heap

Note: Stack can also be called stack

Unlike C/C++, there is no strict sense in JavaScript Distinguish between stack memory and heap memory. Therefore, we can roughly understand that all data in JavaScript is stored in heap memory. But in some scenarios, we still need to process based on the stack data structure, such as JavaScript execution context (I will summarize the execution context in the next article). The execution context logically implements the stack. Therefore, it is still important to understand the principles and characteristics of the stack data structure.

To simply understand the access method of the stack, we can analyze it by analogy with a table tennis box. As shown on the left side of the picture below.

Front-end Advanced (1): Memory Space Diagram

Table tennis box and stack analogy

The storage method of table tennis balls is exactly the same as the method of accessing data in the stack. The table tennis ball 5 at the top of the box must be put in last, but it can be used first. If we want to use the bottom table tennis ball 1, we must take out the four table tennis balls above so that the table tennis ball 1 is on the top level of the box. This is the characteristic of stack space first in, last out, last in first out. The figure has shown the storage principle of stack space in detail.

The way a heap stores and retrieves data is very similar to a bookshelf and a book.

Although the books are neatly stored on the bookshelf, as long as we know the name of the book, we can easily take out the book we want, instead of having to take out the ping pong from the ping pong box. Take out all the ping pong balls on top to get a certain ping pong ball in the middle. For example, in the data in the JSON format, the <a href="http://www.php.cn/wiki/1051.html" target="_blank">key</a>-value we store can be unordered, because the difference in order does not affect our use. Just care about the name of the book.

2. Variable Objects and Basic Data Types

After the JavaScript execution context is generated, a special object called the variable object will be created (the details will be summarized together with the execution context in the next article). JavaScript's basic data types are often stored in variable objects.

Strictly speaking, variable objects are also stored in heap memory. However, due to the special functions of variable objects, we still need to distinguish them from heap memory when understanding them.

Basic data types are simple data segments. There are 5 basic data types in JavaScript, namely Undefined, <a href="http://www.php.cn/wiki/62.html" target="_blank">Null</a>, Boolean, Number, <a href="http://www.php.cn/wiki/57.html" target="_blank">String</a>. Basic data types are accessed by value, because we can directly manipulate the actual value stored in the variable.

3. Reference data types and heap memory

is different from other languages. JS’s reference data types, such as arrays Array, the size of their values ​​is not fixed. Values ​​of reference data types are objects stored in heap memory. JavaScript does not allow direct access to locations in heap memory, so we cannot directly manipulate the heap memory space of an object. When you manipulate an object, you are actually manipulating a reference to the object rather than the actual object. Therefore, values ​​of reference types are accessed by reference. The reference here can be roughly understood as an address stored in the variable object, which is associated with the actual value of the heap memory.

为了更好的搞懂变量对象与堆内存,我们可以结合以下例子与图解进行理解。

var a1 = 0;   // 变量对象
var a2 = 'this is string'; // 变量对象
var a3 = null; // 变量对象

var b = { m: 20 }; // 变量b存在于变量对象中,{m: 20} 作为对象存在于堆内存中
var c = [1, 2, 3]; // 变量c存在于变量对象中,[1, 2, 3] 作为对象存在于堆内存中

Front-end Advanced (1): Memory Space Diagram

上例图解

因此当我们要访问堆内存中的引用数据类型时,实际上我们首先是从变量对象中获取了该对象的地址引用(或者地址指针),然后再从堆内存中取得我们需要的数据。

理解了JS的内存空间,我们就可以借助内存空间的特性来验证一下引用类型的一些特点了。

在前端面试中我们常常会遇到这样一个类似的题目

// demo01.js
var a = 20;
var b = a;
b = 30;

// 这时a的值是多少?
// demo02.js
var m = { a: 10, b: 20 }
var n = m;
n.a = 15;

// 这时m.a的值是多少

在变量对象中的数据发生复制行为时,系统会自动为新的变量分配一个新值。var b = a执行之后,a与b虽然值都等于20,但是他们其实已经是相互独立互不影响的值了。具体如图。所以我们修改了b的值以后,a的值并不会发生变化。

Front-end Advanced (1): Memory Space Diagram

demo01图解

在demo02中,我们通过var n = m执行一次复制引用类型的操作。引用类型的复制同样也会为新的变量自动分配一个新的值保存在变量对象中,但不同的是,这个新的值,仅仅只是引用类型的一个地址指针。当地址指针相同时,尽管他们相互独立,但是在变量对象中访问到的具体对象实际上是同一个。如图所示。

因此当我改变n时,m也发生了变化。这就是引用类型的特性。

Front-end Advanced (1): Memory Space Diagram

demo02图解

通过内存的角度来理解,是不是感觉要轻松很多。除此之外,我们还可以以此为基础,一步一步的理解JavaScript的执行上下文,作用域链,闭包,原型链等重要概念。其他的我会在以后的文章慢慢总结,敬请期待。

内存空间管理

因为JavaScript具有自动垃圾收集机制,所以我们在开发时好像不用关心内存的使用问题,内存的分配与回收都完全实现了自动管理。但是根据我自己的开发经验,了解内存机制有助于自己清晰的认识到自己写的代码在执行过程中发生过什么,从而写出性能更加优秀的代码。因此关心内存是一件非常重要的事情。

JavaScript的内存生命周期

1. 分配你所需要的内存
2. 使用分配到的内存(读、写)
3. 不需要时将其释放、归还

为了便于理解,我们使用一个简单的例子来解释这个周期。

var a = 20;  // 在内存中给数值变量分配空间
alert(a + 100);  // 使用内存
a = null; // 使用完毕之后,释放内存空间

第一步和第二步我们都很好理解,JavaScript在定义变量时就完成了内存分配。第三步释放内存空间则是我们需要重点理解的一个点。

JavaScript有自动垃圾收集机制,那么这个自动垃圾收集机制的原理是什么呢?其实很简单,就是找出那些不再继续使用的值,然后释放其占用的内存。垃圾收集器会每隔固定的时间段就执行一次释放操作。

在JavaScript中,最常用的是通过标记清除的算法来找到哪些对象是不再继续使用的,因此a = null其实仅仅只是做了一个释放引用的操作,让 a 原本对应的值失去引用,脱离执行环境,这个值会在下一次垃圾收集器执行操作时被找到并释放。而在适当的时候解除引用,是为页面获得更好性能的一个重要方式。

  • 在局部作用域中,当函数执行完毕,局部变量也就没有存在的必要了,因此垃圾收集器很容易做出判断并回收。但是全局变量什么时候需要自动释放内存空间则很难判断,因此在我们的开发中,需要尽量避免使用全局变量,以确保性能问题。

  • 要详细了解垃圾收集机制,建议阅读《JavaScript高级编程》中的4.3节


The above is the detailed content of Front-end Advanced (1): Memory Space Diagram. For more information, please follow other related articles on the PHP Chinese website!

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