preface
This chapter continues with the basics of JS in depth following “JavaScript Advancement – Executing Context Stacks and Variable Objects (more on a weekly basis)”.
We’ve talked a lot about execution contexts and variable objects in JS, but now I’m going to talk about the memory space in JS.
In this chapter you will learn:
-
Three types of data structures: heap, stack, queue
-
Storage of variables
-
Memory space management
Three data structures
There are three important data structures in JS, as shown in the figure:
(Image source front-end 956 -Javascript memory space management)
Stack data structure
I’ve already mentioned the stack in JavaScript Execution Context, so let’s review it:
Stack characteristics: Last in first out (LIFO) structure.
(LIFO: last-in, first-out, similar to putting a ball into a ping-pong bucket; the first ball is put in and the last ball is taken out)
Here or stick a network diagram for everyone to understand:
The data in the stack are like ping-pong balls, the first ones in are the last ones out.
Note ⚠ ️
When I say push and push, I don’t mean assign to, use to. It means that assignments go in, they’re cleaned out, and variables that are in the same function scope should be on the same layer of the stack.
The so-called stack of variables stored in stack memory, traditionally refers to the space automatically created and allocated by memory, such as function parameter values and local variables, but its operation mode is similar to stack operation, so it is called stack memory.
For example, function calls are actually stacks:
Example 🌰 :
function fn1() {
console.log(1)
fn2()
}
function fn2() {
console.log(2)
fn3()
}
function fn3() {
console.log(3)
}
fn1()
Copy the code
As above, the order of declaration is 1, 2, 3, but the order of release is 3, 2, 1.
And the reason why this is released in this order is because 3 is the first to be released, so it’s the first to be released.
Heap data structure
A tree like structure. Just like the data in JSON format, you have the key, I have the corresponding value, immediately back to you.
Since we know that JSON storage is out of order, it is an absolutely fair data structure.
As shown in the figure:
Queue data structure
The queue data structure is different from the heap in that the queue is a first-in, first-out (FIFO) data structure.
It is also the infrastructure for Event loops.
As shown in the figure:
The first task in the queue comes out first, similar to when you wait in line to buy a ticket and the first person in line buys first.
Storage of variables
From the above introduction we know, there is a stack in memory, so JS variables are stored in the specific where?
- Basic data types are stored in stack memory;
- Reference data types are stored in heap memory.
- There are 6 basic data types:
Undefined, Null, Boolean, Number, String, Symbol
If you countBigInt
Since they each occupy a fixed amount of space in memory, they are accessed by value. - Reference data types: i.e
Object
Object, whose storage is divided intoAccess to the addressandWhere it’s actually stored; Access addresses are stored inThe stackWhen a query refers to a type variable, the query will first run fromThe stackTo read the memory address (that is, access address), and then through the address to findThe heapSo, this is also what we call thetaReference to access.
A picture for your understanding 🤔
In the data structure of computer, stack is faster than heap. Object is a complex structure and can be expanded: array can be expanded, Object can add attributes, and can be added, deleted, changed, and searched. They are placed in the heap so as not to affect stack efficiency. Instead, it references the actual object in the heap and operates on it. So when looking for a reference type value, look on the stack first and then look on the heap.
Variable storage case
If you’re a little fuzzy after reading the stack store description above, let’s take a look at a few examples.
Case a 🌰 :
var a = 1;
var b = a;
b = 2;
console.log(a); // a = ?
Copy the code
Case 2 🌰 :
var obj1 = { a: 1.b: 2 };
var obj2 = obj1;
obj2.a = 3;
console.log(obj1.a); // obj1.a = ?
Copy the code
Case three 🌰 :
var obj1 = { a: 1 };
var obj2 = obj1;
obj1 = null;
console.log(obj2); // obj2 = ?
Copy the code
The answers of the above three cases are: 1, 3, {a: 1} respectively.
- In case one,
A and b
Both are basic data types, and their values are stored in their own stack space, so they are not affected by each otherb
After the value of thea
It’s still the same.var b = a
The operation of, you can understand as pureb
Value assignment1
And thenA and b
It doesn’t matter any more. - In case 2, create
obj1
Store a stack namedobj1
Variables, while opening up a heap of memory for storing up{a: 1, b: 2}
Object,obj1
Is the address that points to the heap memory object. soobj2
When I do the assignment, I copy justobj1
In, they actually point to objects in heap memory. When you change the value of this object in step 3, you also change it at the same timeobj1
. - In case three, at the beginning,
obj1
andobj2
They’re all pointing to the same heap of memory objects{a: 1}
In the third stepobj1
The assignment fornull
It just changes the stackobj1
The memory address of thenull
, does not affect heap memory objects. Again, you’re going to have toobj1
No assignmentnull
Instead, the value is assigned to{b: 2}
forobj2
It still doesn’t matter.
Variables in closures
Ask ❓: Do all variables follow the rule that “basic data types are stored in the stack and object data types are stored in the heap”?
This is not entirely true, as variables in closures are not stored on the stack, but in the heap.
Because if the variable is in the stack, then the function is destroyed at the top of the stack, and the closure variable is cleared, but what about closure?
Memory space management
We talked about stack memory, heap memory, how to manage this memory space in JS?
First, similarly, memory space also has its own life cycle, which is mainly divided into three phases:
- Allocate the memory you need;
- Use allocated memory (read, write);
- Release and return them when they are not needed.
We can use an example to see that.
Case a 🌰 :
var a = 1; // Allocate space in memory for numeric variables
alart(a + 2); // Use memory
a = null; // Free up memory space after use
Copy the code
The above three steps correspond to three stages. Of course, the operation a = null is manually freeing the memory of A. Without this process, will JS do some memory free work for me? The answer, of course, is yes.
JS has an automatic garbage collection mechanism, which will find values that are no longer in use and then free up memory. The garbage collector performs a release operation at regular intervals.
In automatic garbage collection mechanisms, the most common is to find out which objects are no longer in use through a tag sweep algorithm. In fact, the above I said that a = null manual free memory is not accurate. Because using a = NULL simply frees the reference, the value of a is removed from the execution environment and will be found and freed the next time the garbage collector executes an operation.
Another point is that in a local scope, local variables no longer need to exist after the function has finished executing, and the garbage collector knows that such variables need to be reclaimed, so it is easy to determine.
However, it is difficult to determine when global variables need to free memory space, so in principle we should avoid using global variables in our development.
After the language
Mastering the basic knowledge of MEMORY space in JS can avoid a series of performance problems in the actual development.
Reference article:
Wood – Yang front-end advanced -JavaScript in-depth storage space detailed diagrams
Front end basic advance (1) : memory space detailed diagram
Front-end 956 -Javascript memory space management
About the JS “stack space advanced after out, last in first out” question?
Knowledge is priceless, support original