JavaScript memory management (heap and stack) and JavaScript operating mechanism

Source: Internet
Author: User

Basic Memory Concepts

Life cycle of Memory:

1. Allocate the required memory

2. Memory reading and writing

3, when not needed to release it

The memory life cycle of all languages is basically consistent, except that the final step is clear in low-level languages, but in high-level languages such as JavaScript, this step is hidden and transparent.

JS's Memory life cycle:

1, the memory allocation is completed when the variable is defined

2, the use of the value of the process is actually the allocation of memory read and write operations. Reading and writing can be written to a variable or to an object's property value, or even to the arguments of a function.

3, and the release of memory depends on the GC mechanism (high-level language interpreter embedded "garbage collector").

When the program runs, it needs memory space to hold the data. In general, the system divides two different memory spaces: one is called a stack, and the other is called a heap.

Heap and Stack (stack)

The heap is unstructured and the data can be stored arbitrarily. The heap is used for complex data types (reference types) to allocate space, such as array objects, object objects.

In general, each thread allocates a stack, and each process allocates a heap, that is, the stack is thread-exclusive and the heap is shared by the thread. In addition, when the stack is created, the size is deterministic, the data exceeds this size, and a stack overflow error occurs, and the heap size is indeterminate and needs to be increased continuously.

The stack is structured, each chunk is stored in a certain order (last in, first out), and the stack contains references to some basic types of variables and objects, and the data size and lifetime of the stack must be determined. You can clearly know the size of each chunk, so the stack is addressed faster than the heap.

A function call forms a stack frame.

function Foo (b) {  var a = ten;   return A + B + one;} function Bar (x) {  var y = 3;   return foo (x * y);} Console.log (Bar (7));

When called bar , the first frame is created, bar and the arguments and local variables are included in the frame.

When bar called foo , the second frame is created and pressed onto the first frame, and the frame contains foo the parameters and local variables. When foo returned, the topmost frame is ejected from the stack ( bar the call frame of the function is left).

When it bar returns, the stack is empty.

Stack overflow (stack overflow)

Stack overflow is reported because the stack is limited and the stack exceeds the specified stack limit for the browser. In general, this is not the case, because the JS language has his own GC mechanism, and this situation is usually JS's dead loop or not the correct stop recursion caused, you can debug to track the stack. I have also encountered a C + + Yi Activx control, using event functions to do real-time push stack overflow. The reason is that the event function of the control does not wait until the SHOWMSG function is finished and then pushes, the solution is to push only one at a time, when JS executes and then requests the next push.

function showmsg (msg) {    return msg;} function msgctrl::onmsgntf (msg) {    showmsg ()}  

Heap vs. Stack size

When the program runs, each thread allocates a stack, each process allocates a heap, that is, the stack is thread-exclusive, and the heap is shared by the thread. In addition, when the stack is created, the size is deterministic, the data exceeds this size, and a stack overflow error occurs, and the heap size is indeterminate and needs to be increased continuously. So just look at the stack size limit here. The following is a simple test:

var i=0; function Inc () {    I++    ; if (i>41909) {return;}    Inc ();} Inc ();

The test environment is a computer with 16G of memory, and it is important to note that, depending on the definition of the stack, there will be memory consumption if there is a variable declaration in the INC function.

1, Google Chrome 55.0 version of the browser limit is 41,909.

2, IE8 browser limit is 3,062.

A single thread of JavaScript

One of the main features of the JavaScript language is single-threaded, meaning that only one thing can be done at the same time.

The single thread of JavaScript is related to its purpose. As a browser scripting language, JavaScript's primary purpose is to interact with the user and manipulate the DOM. This determines that it can only be single-threaded, otherwise it can lead to complex synchronization problems. For example, assuming that JavaScript has two threads at the same time, one thread adds content to one of the DOM nodes, and the other thread deletes the node, which thread should the browser take precedence over?

So, to avoid complexity, JavaScript is a single thread from birth, which has become a core feature of the language and will not change in the future.

To take advantage of the computational power of multicore CPUs, HTML5 proposes a web worker standard that allows JavaScript scripts to create multiple threads, but the child threads are completely controlled by the main thread and must not manipulate the DOM. So, this new standard does not change the nature of JavaScript single threading.

Event-loop (Event loop)

A single thread means that all tasks need to be queued, and the previous task is completed before the latter one is executed. If the previous task takes a long time, the latter task has to wait.

If the queue is because of large computational capacity, the CPU is not busy, but also forget, but many times the CPU is idle, because the IO device (input) is very slow (such as the Ajax operation from the network to read data), have to wait for the results, and then down to execute.

The designer of the JavaScript language realizes that at this point the main thread can completely ignore the IO device, suspend the waiting task, and first run the task that is in the queue. Wait until the IO device returns the result, and then go back and put the suspended task on hold.

Thus, all tasks can be divided into two types, one synchronization task (synchronous) and one asynchronous task (asynchronous). A synchronization task is a task that is queued on the main thread to perform the latter task only if the previous task is completed, and the asynchronous task refers to a task that goes into the task queue without entering the main thread, and only the task queue notifies the main thread that an asynchronous task can execute. The task will not go into the main thread execution.

Common asynchronous tasks are AJAX operations, timers (Settimeout/setinterval), UI events (load (image js file loading, etc.), resize, scroll, click, etc.). There are articles on the Internet that say the timer is another thread in parallel execution is not right, here is a simple test:

SetTimeout (function() {Console.log (111)},5); Console.log(new  Date (). GetTime ())  for (var i=0; i<10000000; i++) {}console.log (new  Date (). GetTime ()) Console.log (777);

Operation Result:

You can see that tasks in the task queue are performed only after the main thread has finished executing.

Specifically, the operating mechanism for asynchronous execution is as follows. (Synchronous execution is also true because it can be treated as asynchronous execution without an asynchronous task.) )

(1) All synchronization tasks are performed on the main thread, forming an execution stack (execution context stack).

(2) In addition to the main thread, there is a task queue. As long as the asynchronous task has a running result, an event is placed in the task queue.

(3) Once all the synchronization tasks in the "execution stack" have been executed, the system reads the "task queue" to see what events are in it. Those corresponding asynchronous tasks, so end the wait state, go to the execution stack, and start execution.

(4) The main thread constantly repeats the third step above.

is the main thread and the task queue.

As long as the main line Cheng, will read "task queue", this is the operation mechanism of JavaScript. This process is repeated.

JavaScript memory management (heap and stack) and JavaScript operating mechanism

Related Article

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.