This is the 102nd original without water. If you want to get more original good articles, please search the official and follow us~ This article was first published on the Zheng Caiyun front-end blog: 160f247bec2ea7 v8 The process of executing js
Preface
This article is intended to briefly introduce the process of executing JS in V8. By understanding the process of executing JS in V8, you can know what the JS code is displayed on the browser. Of course, I am also exploring V8 one after another. If there is any impropriety in the article, I hope to make corrections and communicate rationally.
As we all know, the machine (CPU) can only recognize the machine code (binary code), but it cannot recognize the JS code, so when the code becomes a page and appears on the screen, it must do a lot of translation work.
V8 execute Javascript process
As shown in the figure above, we will split the analysis step by step:
JS TO AST
After the V8 engine gets the JS code, the parser (Parser) will perform lexical analysis and grammatical analysis on it.
lexical analysis
Split the JS code into corresponding Tokens. Token is the smallest unit that can be split. The fixed type represents the type/attribute, and the value represents the corresponding value, as shown in the Token below.
#### Parsing
After the lexical analysis is converted to Token, the parser continues to generate the corresponding AST based on the generated Token. AST believes that the front-end students are not unfamiliar, and it is also one of the hot words, whether it is the representation of virtual DOM in Vue, React, or Babel The representation of JS translation is to first convert it into the corresponding AST. The AST structure after parsing by the parser is shown in the following figure:
As you can see, a very small code snippet is much more complicated after being parsed into an AST. The AST in the figure is just a simplified data. The entire AST actually has many parameters, which will be more complicated.
Bytecode
After the parser (Parser) parses the JS code into AST, the interpreter (Ignition) generates bytecode (also called intermediate code) according to the AST. As mentioned earlier, the CPU can only recognize the machine code, but it cannot recognize the bytecode. Here is a problem. If the CPU cannot recognize the bytecode, why do you need to insert a step in the middle to consume resources to convert the bytecode? ? Isn’t the efficiency much lower?
When talking about efficiency in computer science, you can’t escape the two concepts of time and space. Most of the optimizations are space-for-time and time-for-space. The balance between the two and how to achieve the highest efficiency is a worthy of in-depth study. problem.
Take the previous version of the V8 engine to execute JS, there is no bytecode conversion step, directly from AST to machine code, this process is called the compilation process, so every time you get the JS file, it will first be compiled , And this process is relatively time-consuming. This is a headache and requires a solution.
A webpage is opened for the first time, closed and opened again. In most cases, it is still consistent with the original JS file, unless the developer modifies the code, but this can be ignored for the time being, after all, no website will be boring for a day. Constantly modify, upload and replace.
Cache machine code
According to this idea, since the file will not be modified in most cases, the compiled machine code can be cached. In this way, the next time you open or refresh the page, the compilation process will be omitted, and you can directly The machine code is stored in two cases. One is when the browser is not closed, it is directly stored in the browser’s local memory, the other is when the browser is closed, and it is stored directly on the disk, and the early V8 is also true This is done, typically at the expense of space for time.
Problems caused by caching
Consider a question. As you can see from the above figure, a small code snippet becomes a lot bigger after being converted into an AST. The larger the file causes a problem that requires more memory to store, and the JS file is converted into The machine code (ie binary file) will be hundreds or even thousands of times larger than the original JS file, which means that a JS file of tens of KB will reach tens of MB. This is terrible. The original Chrome multi-process architecture It already takes up a lot of memory. If you come to this one, no matter how well-configured your computer is, you may not be lucky enough to suffer from Chrome. After all, the quality of the user experience directly determines whether a product can survive in the market, even though V8 The compiled code is cached, which reduces compilation time and improves time efficiency, but the cost is that the memory footprint is too large, so it is necessary for the Chrome team to optimize this problem.
Lazy compilation
Of course, the introduction of other technologies requires time to develop and optimize. When a technical architecture is generated, there will inevitably be made up for disadvantages. In order to solve the problem of memory occupation and startup speed, the early version of V8 introduced lazy compilation . So the question is, lazily compiled done to improve efficiency?
lazy compilation is still relatively easy to understand. From the perspective of scope, ES6 had only global scope and function scope before, and lazy compilation is to only compile and cache the code of the global scope when V8 starts , And the code in the function scope will be compiled when it is called, and the compiled code inside the function will not be cached.
Problems with lazy compilation
After the introduction of lazy compilation , in terms of compilation speed and cache, it has been improved, everything seems to be perfect, yes, it looks, but you never know how the user will use the design. Before the popularization of ES6, Vue, React, etc., most developers used jQuery, RequireJS and other similar products, various references of JQ plug-ins, various plug-ins or the developer’s own packaging methods, in order not to pollute Variables of other users are generally encapsulated into a function, so the problem comes. lazy compilation will not save the machine code after the function is compiled and understand the compiled function. If a plug-in is too large, wait until the function is used to compile it. Compilation time will become very slow, which is equivalent to the developer has lazily compiling , and the road is blocked.
Introducing bytecode
Well, I can't play with developers, so the V8 team had to change their mindset and introduce bytecode. First of all, we must understand what bytecode is. Bytecode is actually an abstraction of machine code. The mutual composition of various bytecodes can realize all the functions required by JS. Of course, the first point is that bytecode takes up more memory than machine code. It is much smaller, basically tens or even a few percent of the memory where the machine code is located, so that the memory consumed by the bytecode cache is still acceptable.
There is a question here. Since the CPU cannot recognize the bytecode, is it necessary to convert the bytecode into machine code? Otherwise, the answer is yes. Explain that after the AST is converted to bytecode, the bytecode will be converted into machine code during execution. This execution process is definitely slower than directly executing machine code, so in terms of execution, the speed will be slower. But the JS source code is converted to AST through the parser, and then the bytecode is converted through the interpreter. This process is much faster than the compiler directly converts the JS source code to machine code. From the perspective of the whole process, the whole time is not much different. , But it reduces a lot of memory usage, why not do it.
translater
Hot code
In the code, the same part of the code is often called multiple times. If the interpreter needs to convert the binary code to execute the same part of the code every time, it will be a bit wasteful in terms of efficiency, so there will be a special in the V8 module. Monitoring module, to monitor whether the same code is called multiple times, if it is called multiple times, it will be marked as hot code , what does this do?
Optimizing compiler
TurboFan (Optimizing Compiler) This term is believed to be familiar to students who pay attention to the mobile phone industry. Brands such as Huawei and Xiaomi have appeared in product launch conferences in recent years. The main ability is optimized through software computing power. A series of functions make the efficiency better.
Then the hot code continues to say that when there is a hot code, V8 will use TurboFan to convert the bytecode of the hot code into machine code and cache it, so that when the hot code is called again, there is no need to change the word The code is converted to machine code. Of course, the hot code is relatively small, so the cache does not take up too much memory, and the execution efficiency is improved. Also here is the sacrifice of space for time.
Anti-optimization
JS language is a dynamic language, very flexible, the structure and properties of the object can be changed at runtime, imagine a problem, if the hot code is executed at a certain time, suddenly one of the attributes is modified, then compile Can the hot code that is machine code continue to execute? The answer is definitely not. At this time, the anti-optimization the optimizing compiler will be used. He will return the hot code to the AST step. At this time, the interpreter will reinterpret and execute the modified code. If the code is marked as hot code again, then This step of the optimizing compiler will be repeated.
to sum up
From the analysis process, the process of V8's execution of JS not only uses an interpreter, but also an optimizing compiler. This combination of the two is called JIT (Just-In-Time) in the industry. Using this combined method to process JS is mainly because the files formed by the AST are smaller, and the hot code compiled by the optimizing compiler has high execution efficiency. The combination of the two, each exerts its own advantages, and improves the efficiency as much as possible. maximum.
What V8 does is much more than that. Here is just a brief overview and analysis of some of the things done in the main process. If you refine each point, there are many concepts, such as inline caching, hidden classes, Fast attributes, slow attributes, creating objects, and the garbage collection author wrote before, etc., have done too many things, so I won’t list them one by one.
Open source works
- Front-end tabloid of Zheng Caiyun
open source address www.zoo.team/openweekly/ (WeChat exchange group on the homepage of the tabloid official website)
Recruitment
ZooTeam, a young, passionate and creative front-end team, is affiliated to the product development department of Zheng Caiyun. The Base is located in picturesque Hangzhou. The team now has more than 40 front-end partners with an average age of 27 years old. Nearly 30% are full-stack engineers, a proper youth storm troupe. The membership consists of not only “veteran” soldiers from Ali and Netease, as well as newcomers from Zhejiang University, University of Science and Technology of China, Hangzhou Electric Power and other schools. In addition to the daily business docking, the team also conducts technical exploration and actual combat in the material system, engineering platform, building platform, performance experience, cloud application, data analysis and visualization, and promotes and implements a series of internal technical products. Explore the new boundaries of the front-end technology system.
If you want to change that you have been tossed by things, hope to start to toss things; if you want to change and have been warned, you need more ideas, but you can’t break the game; if you want to change you have the ability to make that result, but you don’t need you; if If you want to change what you want to accomplish, you need a team to support it, but there is no position for you to lead people; if you want to change the established rhythm, it will be "5 years of work time and 3 years of work experience"; if you want to change the original The comprehension is good, but there is always the ambiguity of the window paper... If you believe in the power of belief, believe that ordinary people can achieve extraordinary things, believe that you can meet a better self. If you want to participate in the process of business take-off, and personally promote the growth of a front-end team with in-depth business understanding, complete technical system, technology to create value, and influence spillover, I think we should talk. Anytime, waiting for you to write something, send it to ZooTeam@cai-inc.com
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。