directory

  1. JS is an interpreted language
  2. Engine handling of JSLexical analysis -> Get the token -> Syntax analysis -> Get the AST -> The translator -> Bytecode -> Bytecode interpreter -> Machine code
  3. JS preprocessing stage [incomplete semicolon, variable promotion]
  4. The execution stage of JS [execution context, VO (variable object) and AO (active object), scope chain] in the context of functions:VO === AOIn the global context:VO === this === global
  5. Garbage collection mechanism GC
  6. reference
  7. conclusion

JS is an interpreted language

JS is interpreted speech, so it doesn’t need to be compiled ahead of time and is run in real time by the interpreter

JS needs engine parsing

The JS processing process of the two engines can be summarized as follows:

1.The code is read, Lexical analysis is performed, and then the code is broken down into tokens2.Parsing the primitives, and then arranging the code into a syntax tree.3.Convert code to bytecode using a translator4.The bytecode is converted into machine code using the Bytecode interpreterCopy the code

Lexical analysis -> get token -> Parse -> get AST -> translator -> Bytecode -> bytecode interpreter -> machine code

Ultimately, the computer executes machine code.

Modern browsers generally use JIT-Just In Time compiler to improve performance.

That is, bytecode is compiled only at runtime, which line is used, and the compiled results are cached inline cache.

So the speed of the whole program can be significantly improved.

Also, different browsers may have different policies. Some browsers skip the bytecode translation step and convert directly to machine code (e.g. Chrome’s V8)

To summarize, the core JIT compiler compiles the source code into machine code to run it

Three JS pre-processing stage

1 Semicolon completion

2 Variable lifting

This is the overall process of the interpreter, but there is also a pre-processing phase (e.g. variable promotion, semicolon completion, etc.) before JS is executed.

The preprocessing phase does a few things to ensure that JS executes correctly, just to name a few:

The semicolon completion

JS execution requires semicolons, but why does the following statement work?

console.log('a')
console.log('b')

Copy the code

The JS interpreter has a Semicolon Insertion rule that adds semicolons at appropriate positions according to certain rules

Here are a few rules that automatically add semicolons:

  • When there is a newline character (including a multi-line comment containing a newline character), and the nexttokenA semicolon is automatically added if the preceding syntax does not match.
  • When you have}If the semicolon is missing, the semicolon is added.
  • At the end of the program’s source code, a semicolon is added if it is missing.

So, the code above becomes

console.log('a');
console.log('b');

Copy the code

So it works

Of course, here’s a classic example:

function b() {
    return
    {
        a: 'a'
    };
}

Copy the code

Because of the semicolon completion mechanism, it becomes:

function b() {
    return;
    {
        a: 'a'
    };
}

Copy the code

So it runs undefined

Variable ascension

Generally including function promotion and variable promotion

Such as:

a = 1;
b();
function b() {
    console.log('b');
}
var a;

Copy the code

After variable enhancement, it becomes:

function b() {
    console.log('b');
}
var a;
a = 1;
b();

Copy the code

There’s no expansion here, but expansion can involve a lot of things

Examples include variable declarations, function declarations, parameters, priority order of arguments, and temporary dead zones related to lets in ES6

Four JS execution stages

Understanding JavaScript series 10: the Core of JavaScript

After the interpreter interprets the grammar rules, it begins execution, and the following concepts are generally included in the execution process:

  • Execute context, execute stack concepts (e.g., global context, current active context)
  • VO (variable object) and AO (active object)
  • The scope chain
  • This mechanism etc.

These concepts are too much to explore in depth, so only a few features are mentioned here

The execution context is explained briefly

  • JS haveExecution context
  • The browser first loads the script it will createGlobal execution contextAnd push to the top of the execution stack (cannot be ejected)
  • Each time it enters another scope, it creates the corresponding execution context and pushes it to the top of the execution stack
  • Once the corresponding context is executed, it pops off the top of the stack and gives context control to the current stack.
  • Execute in sequence (eventually returning to the global execution context)

For example, if the program completes execution, is thrown off the stack, and then is not referenced (no closure is formed), the memory used in this function is automatically reclaimed by the garbage processor

The relationship between the execution context and VO, scope chain, this is:

Each execution context has three important properties:

  • Variable object (The Variable object, VO)
  • Scope chain (Scope chain)
  • this

VO with AO

VO is an attribute of the execution context (abstract concept), but only the variable objects of the global context are allowed to be accessed indirectly through the VO attribute name (because in the global context, the global object is itself a variable object).

The AO (ACTIVATION object) is created when the function is activated by the caller

It can be understood as:

  • In the context of functions:VO === AO
  • In the global context:VO === this === global

In general, VO stores variable information (declared variables, functions, arguments, etc.)

The scope chain

It is an attribute in the execution context, similar in principle to a prototype chain, and is very important.

For example, process brief:

In the function context, look for a variable foo. If it is found in the VO of the function, use it directly. Otherwise, look in its parent scope chain (__parent__)Copy the code

This pointer

This is also one of the core knowledge of JS, because the content is too much, here will not expand, only mention part

Note: This is a property of the execution context, not of a variable object

Therefore:

  • There is no such thing as a search for variables
  • When this is used in code, the value of this is taken directly from the execution context, rather than being searched through the scope chain
  • The value of this depends only on the context in which the

So the classic example:

var baz = 200; var bar = { baz: 100, foo: function() { console.log(this.baz); }}; var foo = bar.foo; // Enter the environment: global foo(); // 200, Cannot read property 'baz' of undefined // global bar bar.foo(); / / 100Copy the code

The above example is easy to understand

More references:

Deeper understanding of JavaScript Series (13) : This? Yes,this!

5. Garbage Collection mechanism GC

JS has a garbage handler, so there is no need to reclaim memory manually, but it is handled automatically by the garbage handler.

Generally speaking, garbage handlers have their own collection policies.

For example, functions that have completed execution will be reclaimed if there are no external references (which would form closures). (Of course, the recovery action is generally cut to different time periods to avoid affecting performance)

Two common garbage collection rules are:

  • Mark clear
  • Reference counting

The basic GC scheme for the Javascript engine is simple GC: Mark and sweep.

  1. Iterate over all accessible objects.
  2. Reclaim objects that are no longer accessible.

For example :(from javascript elevation)

When a variable enters the environment, for example, declaring a variable in a function, mark the variable as “entering the environment.”

Logically, you can never free up memory occupied by variables that enter the environment, because they may be used whenever the execution stream enters the corresponding environment.

When a variable leaves the environment, it is marked as “out of the environment.”

At run time, the garbage collector marks all variables stored in memory (of course, it can be marked in any way).

It then unflags variables in the environment and variables referenced by variables in the environment (closures, that is, variables referenced in and around the environment are unmarked).

Variables tagged after this point are considered to be ready for deletion because they are no longer accessible to variables in the environment.

Finally, the garbage collector completes the memory cleanup, destroying the tagged values and reclaiming the memory space they occupy.

About reference counting, a simple understanding:

Track how many times each value is referenced and, when a value is referenced, how many times+ 1, underweight- 1, the next garbage collector will collect times is0(of course, easy to loop reference bug)

The defect of the GC

As with other languages, javascript’s GC strategy is not immune to the problem of stopping to respond to other operations while GC is in progress

This is for safety reasons.

Javascript GC is 100ms or more

For the general application is good, but for JS games, animation on the coherence requirements of the application is high, it is troublesome.

This is where the engine needs to be optimized: to avoid long pauses in response caused by GC.

GC optimization strategy

Generation GC (Generation GC)

The aim is to distinguish between “temporary” and “permanent” objects:

  • Multiple reclaim temporary Objects area (young generation)
  • Recycle less persistent Objects section (tenured generation)
  • Reduce the number of objects to traverse each time, thereby reducing the time of each GC.

The Node V8 engine uses generational recycling (like Java, the author is the Java virtual machine author).

For more information:

V8 Memory Analysis

Six reference

  • The process from entering the URL to page loading

Seven summarizes

  • JS is an interpreted language
  • The engine handles JS:Lexical analysis -> Get the token -> Syntax analysis -> Get the AST -> The translator -> Bytecode -> Bytecode interpreter -> Machine code
  • JS preprocessing stage [incomplete semicolon, variable promotion]
  • The execution stage of JS [execution context, VO (variable object) and AO (active object), scope chain] in the context of functions:VO === AOIn the global context:VO === this === global
  • Garbage collection mechanism GC