How JavaScript works (JavaScript works) (vi) WebAssembly vs. JavaScript and its usage scenarios

Source: Internet
Author: User
Tags abstract tree

Personal Summary:

1.webassembly Introduction: Webassembly is an efficient, low-level bytecode for developing network applications. Allows languages other than JavaScript (such as C,c++,rust and other) to be used in Web applications to write applications and then compile (early) WebAssembly.

This is the sixth chapter of how JavaScript works.

Now, we'll dissect how WebAssembly works, and most importantly, its performance with JavaScript: Load time, execution speed, garbage collection, memory usage, platform API access, debugging, multithreading, and portability.

We are facing a change in the way we build our web programs-it's just the beginning and our way of thinking about Web applications is changing.

First, get to know the WebAssembly.

WebAssembly (also known as WASM) is an efficient, bottom-level bytecode for developing network applications.

WASM lets you write applications in languages other than JavaScript (such as C, C + +, Rust, and others), and then compile (early) WebAssembly.

The built-in Web application loads and runs very quickly.

Load time

In order to load JavaScript, the browser must load all text-formatted JS files.

The browser will load the WebAssembly more quickly because WebAssembly only transmits the wasm files that have been compiled. And Wasm is the underlying class assembly language, with a very compact binary format.

Execution speed

Today, Wasm runs only 20% slower than native code. In any case, this is a surprising result. It is a format that is compiled into a sandbox environment and runs under a number of constraints to ensure that there are no security holes or enhancements. Compared to real native code, the speed of execution is minimal. In addition, the future will be much faster.

What's even more pleasing is that it has good browser compatibility-all major browser engines support WebAssembly and run very fast.

In order to understand how fast the WebAssembly executes in comparison to JavaScript, you should first read the article on how the previous JavaScript engine works.

Let's take a quick look at the operating mechanism of the V8:

V8 Technology: Lazy Compiling

On the left is the JavaScript source, which contains JavaScript functions. First, the source code first converts the string to a token to facilitate parsing, and then generates a syntax abstract tree.

The syntax abstract tree is a diagram of the JavaScript program logic in memory. Once the diagram is generated, V8 directly into the machine code phase. You basically traverse the tree, generate the machine code, and then get the compiled function. There is no real attempt to speed up the process.

Now, let's take a look at the work of the next phase of the V8 pipeline:

V8 Piping Design

Now that we have turbofan, it is one of the V8 optimization compilers. When JavaScript is running, a lot of code runs inside V8. Turbofan monitors slow-running code, where and hotspots that cause performance bottlenecks (where memory usage is too high) to optimize them. It pushes the above-monitored code to the backend, the optimized instant compiler, which translates functions that consume a lot of CPU resources into better-performing code.

It solves the problem of performance, but the drawback is that the process of parsing code and identifying which code needs to be optimized also consumes CPU resources. This means more power consumption, especially in mobile devices.

However, Wasm does not require all of the above steps-it is inserted as follows in the execution process:

V8 Piping Design + WASM

WASM has passed code optimization during the compilation phase. In short, the resolution is not necessary. You have optimized binary code that can be inserted directly into the backend (instant compiler) and generate machine code. The compiler has done all the code optimization work on the front end.

This makes wasm execution more efficient by skipping a number of steps in the compilation process.

Memory model

WebAssembly Trusted and untrusted status

For a chestnut, the memory of a C + + program is compiled into WebAssembly, which is a contiguous block of memory without holes. There is a concept in Wasam that can be used to improve code security, which is the execution stack and linear memory isolation. In a C + + program, you have a dynamic memory area where you allocate the memory stack from the bottom, and then get the memory from the top of it to increase the size of the memory stack. You can get a pointer and then traverse through the stack memory to manipulate variables that you should not touch.

This is a vulnerability that most suspicious software can exploit.

The WebAssembly uses a completely different memory model. The execution stack and the WebAssembly program itself are isolated, so you can't modify and change the value of a variable from inside. Similarly, the function uses an integer offset instead of a pointer. The function points to an indirect function table. After that, these direct computed numbers enter the function in the module. That's how it works, so you can introduce multiple WASM modules at the same time, offset all indexes, and each module works well.

More articles on JavaScript memory models and management are here.

Memory Garbage Collection

You already know that the memory management of JavaScript is handled by the memory garbage collector.

WebAssembly the situation is a little different. It supports the language of manual memory manipulation. You can also have a memory garbage collector built into the Wasm module, but this is a complex task.

Currently, WebAssembly is designed around the usage scenarios of C + + and RUST. Since Wasm is a very low-level language, it means that programming languages that are higher than assembly language can easily be compiled into WebAssembly. The C language can use malloc,c++ to use smart pointers, and Rust uses completely different patterns (a completely different topic). These languages do not use the memory garbage collector, so they do not need all the complex runtime things to track memory. WebAssembly is a natural fit for these languages.

In addition, these languages are not able to be applied 100% to complex JavaScript usage scenarios such as listening to DOM changes. It is meaningless to write the entire HTML program in C + + because C + + is not designed for this purpose. In most cases, engineers use C + + or Rust to write WebGL or highly optimized libraries (such as a large number of mathematical operations).

However, in the future WebAssembly will support languages without the memory garbage back feature.

Platform Interface Access

Depending on the runtime environment in which JavaScript is executed, the specified interfaces exposed by these platforms can be accessed directly through JavaScript programs. For example, when you run JavaScript in a browser, the Web app can invoke a series of web interfaces to control the browser/device functionality and access the Dom,cssom,webgl,indexeddb,web Audio API, among other things.

However, the WebAssembly module does not have access to any platform interface. All of this has to be coordinated by JavaScript. If you want to access some of the specified platform interfaces within the WebAssembly module, you have to make calls through JavaScript.

For a chestnut, if you want to use it console.log , you have to call it through JavaScript instead of C + + code. These JavaScript calls can have some performance penalty.

The situation will not be invariable. The specification will provide an interface for WASM to access the specified platform in the future, so that you can not have JavaScript built into the program.

SOURCE Mapping

When you compress the JavaScript code, you need to have the appropriate method for debugging.

This is where the source map comes in handy.

In general, source mapping is a way to map a merged/compressed file to a non-constructed state. When building code for a production environment, together with the compression and merging of JavaScript, a source map is generated to hold the original file information. When you want to query the code of a particular row and column in the generated JavaScript code, you can find it in the source map to get the original location of the code.

Because there is no canonical definition of source mapping, WebAssembly is not supported at the moment, but it will eventually (probably faster).

When you set breakpoints in C + + code, you see C + + code instead of WebAssembly. At least, this is the target of the WebAssembly source mapping.

Multithreading

JavaScript is single-threaded. There are many ways to take advantage of event loops and use asynchronous programming mentioned in previous articles.

JavaScript also uses web Workers but only in extremely special cases-in general, you can hand over any dense CPU computation that might block the main thread of the UI to Web Worker execution for better performance. However, WEB workers do not have access to the DOM.

Currently WebAssembly does not support multithreading. However, this could be the next WebAssembly to be implemented. Wasm will be close to implementing native threads (for example, C + + style threads). Having a real thread will create a lot of new opportunities in the browser. And of course, it increases the likelihood of abuse.

Portability

Now JavaScript can run almost anywhere, from the browser to the server or even the embedded system.

The WebAssembly design is designed for security and portability. Just like JavaScript. It will run in any environment that supports WASM, such as every browser.

WebAssembly has the same goal of using Applets to achieve portability in the early years of Java.

WebAssembly Usage Scenarios

The original version of WebAssembly was primarily designed to solve a large number of computationally intensive computations (such as dealing with mathematical problems). The most mainstream usage scenario is game-processing a large number of pixels.

You can use your familiar OpenGL bindings to write C++/rust programs, and then compile them into wasm. After that, it can be run in the browser.

Browse under (run in the fire solitary)-http://s3.amazonaws.com/mozilla-games/tmp/2017-02-21-suntemple/suntemple.html. This is run on Unreal Engine (a development kit that can be used to develop virtual reality).

Another scenario where WebAssembly (high performance) is reasonably used is to implement some computationally intensive libraries. For example, some graphics operations.

As mentioned earlier, WASM can effectively reduce the power consumption of mobile devices (depending on the engine), since most of the steps have been processed in advance in the compile phase.

In the future, you can directly use the WASM binary library even if you did not write code compiled into it. You can find some projects to start using this technology on NPM.

For manipulating the DOM and using the platform interface frequently, JavaScript is more reasonable because it does not incur additional performance overhead and it natively supports a variety of interfaces.

At Sessionstack we have been working to continuously improve the performance of JavaScript to write high-quality and efficient code. Our solutions must have lightning-like performance because we cannot affect the performance of our user programs. Once the sessionstack is integrated into the production environment of a Web application or website, it begins to record everything: all DOM changes, user interactions, JavaScript exceptions, stack traces, failed network requests, and debug data. All of this is produced in a production environment and does not affect any interaction and performance of the product. We must greatly optimize our code and let it execute asynchronously as much as we can.

We have not only a library, but also other features! When you replay a user session in Sessionstack, we must render everything that happens to the user's browser when the problem occurs, and we must refactor the entire state, allowing you to jump back and forth on the session timeline. To make this possible, we use asynchronous operations in large numbers because there is no better alternative to JavaScript.

With WebAssembly, we can hand over a large amount of data computation and rendering to a more appropriate language for processing and handing over data collection and DOM manipulation to JavaScript.

Foreign articles

Open the Webassembly official website to see the browser that shows it compatible in the head. Respectively, the fire is solitary, Chrome,safari,ie Edge. Click to open learn more to see which was agreed in 2017/2/28 to launch the browser preview version. Now that the work is in the implementation phase, it is believed that it can be used in the production environment at some point in the future. The official web site describes a subset of JavaScript Asm.js. In addition, there is a test site for WebAssembly and JavaScript for performance comparison.

How JavaScript works (JavaScript works) (vi) WebAssembly vs. JavaScript and its usage scenarios

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.