JS Memory Space Detailed illustration

Source: Internet
Author: User

JS Memory Space Detailed illustration


Variable Object vs. heap memory
var a = 20;var b = ‘abc‘;var c = true;var d = { m: 20 }

Because JavaScript has an automatic garbage collection mechanism, memory space is not a frequently mentioned concept for front-end development, and is easily overlooked. In particular, many are not computer professional friends in the front end, the memory space will be more ambiguous cognition, and even some people simply is ignorant.

Including myself, of course. For a long time, the concept of memory space is not so important in JS learning. But after I looked back to reorganize the JS Foundation, I found that because of their vague cognition, led to a lot of things I understand not understand. such as the most basic reference data types and reference delivery in the end what is going on? For example, what is the difference between shallow copy and deep copy? There are closures, prototypes and so on.

So then I gradually understand that in order to understand JS more deeply, we must have a clear understanding of memory space.

First, stack and heap

Note: Stacks, can also be called stacks

Unlike C + +, JavaScript does not differentiate stack memory from heap memory in a strict sense. So we can understand that all of the data for JavaScript is stored in heap memory. But in some scenarios, we still need to deal with the idea of stack data structures, such as JavaScript's execution context (I'll summarize the execution context in the next article). The execution context logically implements the stack. Therefore, it is important to understand the principle and characteristics of the stack data structure.

To simply understand how stacks are accessed, we can analyze them by analogy with table tennis boxes. As on the left.


Table tennis box and stack analogy

The table tennis is stored in the same way that the data is accessed in the stack. The top-level table tennis in the box is 5, it must be put in at the end, but can be used first. And we want to use the bottom of the table tennis 1, it must be the above 4 table tennis out, so that table tennis 1 in the box on the top floor. This is the stack space advanced, after the first out of the characteristics. The storage principle of stack space is shown in detail in the diagram.

The way the heap accesses data is very similar to the bookshelf and the book.

Although the book is also neatly stored on the shelves, but we just know the name of the book, we can easily take out the books we want, instead of playing table tennis from a ping pong box, we have to take all the above table tennis to get the middle of a table tennis. As in JSON-formatted data, we can store the key-value disorder, because the difference in order does not affect our use, we only need to care about the name of the book.

Ii. variable objects and underlying data types

After the JavaScript execution context is generated, a special object called a variable object is created (which is summarized in the next article with the execution context), and JavaScript's underlying data types are often stored in variable objects.

In the strict sense, variable objects are also stored in heap memory, but due to the special functions of variable objects, we still need to distinguish them from heap memory when we understand them.

The underlying data types are simple data segments, with 5 of the underlying data types in JavaScript, respectively Undefined、Null、Boolean、Number、String . The underlying data type is accessed by value, because we can manipulate the actual values that are stored in the variable directly.

III. reference data Types vs. heap memory

Unlike other languages, JS has reference data types, such as array arrays, whose values are not fixed. The value of the reference data type is the object that is saved in heap memory. JavaScript does not allow direct access to the location in the heap memory, so we cannot manipulate the object's heap memory space directly. When you manipulate an object, you are actually manipulating the object's reference rather than the actual object. Therefore, the value of the reference type is accessed by reference. Here, we can superficially understand an address that is stored in a variable object, which is associated with the actual value of the heap memory.

To better understand the variable object and heap memory, we can combine the following examples and diagrams to understand.

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] 作为对象存在于堆内存中

Example illustration above

So when we want to access the reference data type in heap memory, we actually first get the object's address reference (or address pointer) from the variable object, and then we get the data we need from the heap memory.

Understanding the memory space of JS, we can use the characteristics of memory space to verify some of the characteristics of the reference type.

In front of the interview we often encounter such a similar problem

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

When the data in a variable object replicates, a new value is automatically assigned to the new variable. var b = aafter execution, a and B, although the values are equal to 20, but they are in fact independent of each other's values. Specific. So when we change the value of B, the value of a does not change.


DEMO01 diagram

In Demo02, we var n = m perform a copy of the reference type operation. A copy of a reference type will also automatically assign a new value to the new variable to be saved in the variable object, but the difference is that this new value is just an address pointer to a reference type. When the address pointers are the same, even though they are independent of each other, the specific object accessed in the variable object is actually the same:

So when I changed N, M also changed. This is the attribute of the reference type.


DEMO02 diagram

It is not a lot easier to understand through the memory angle. In addition, we can use this as a basis for a step-by-step understanding of JavaScript execution context, scope chain, closures, prototype chain and other important concepts. Other I will be in the future article slowly summed up, please look forward to.

Memory Space Management

Because JavaScript has an automatic garbage collection mechanism, we do not seem to be concerned about the use of memory in development, and the allocation and recycling of memory is fully automated. But based on my own development experience, understanding the memory mechanism helps me to clearly understand what is going on in the execution of the code that I write, and write code that performs better. So caring for memory is a very important thing.

The memory life cycle of JavaScript

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

For ease of understanding, we use a simple example to explain this cycle.

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

The first and second steps are well understood, and JavaScript completes the memory allocation as it defines the variables. The third step to freeing up the memory space is one point we need to focus on understanding.

JavaScript has an automatic garbage collection mechanism, so what is the principle of this automatic garbage collection mechanism? The simple thing is to find the values that are no longer in use, and then release the memory they occupy. The garbage collector performs a release operation every fixed period of time.

In JavaScript, the most common is to find out which objects are no longer in use by the algorithm of the tag cleanup, so it's a = null just a matter of releasing the reference, leaving the value of a to be referenced, out of the execution environment, This value is found and freed the next time the garbage collector performs the operation. De-referencing at the right time is an important way to get better performance for your page.

  • In a local scope, when the function is executed, the local variables are not necessary, so the garbage collector can easily make judgments and reclaim them. However, it is difficult to judge when global variables need to automatically free up memory space, so in our development we need to avoid using global variables to ensure performance problems.
  • To learn more about the garbage collection mechanism, it is recommended that you read section 4.3 of JavaScript advanced programming

JS Memory Space Detailed illustration

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.