Preliminary Exploration of webAssembly | JD Logistics Technical Team

1 What is WebAssembly?

A new type of code that runs in modern web browsers and offers new performance features and effects

A web standard developed by the W3C WebAssembly Community Group, for browsers, WebAssembly provides a way to allow code written in various languages ​​​​to run on the Web at near-native speed. In this case, client software, etc. that previously could not run in this way will work on the Web.

From the beginning of its design, WebAssembly decided to run together with JavaScript - through the WebAssembly API in JavaScript, it is possible to load WebAssembly modules into a JavaScript application and call each other between the two. This allows the high performance of WebAssembly and the high flexibility of JavaScript to be used in the same application.

2 Why do you need WebAssembly?

We all know that JavaScript is an interpreted language. Compared with compiled languages, it needs to be converted at runtime, so the execution speed of interpreted languages ​​​​is slower than that of compiled languages.

The specific flow of compiled language and interpreted language code execution is as follows:

Because the interpreted language needs to convert the source code once every time it is executed, and the conversion process is very time-consuming and performance-consuming, it also makes it impossible for the web to execute some high-performance applications in the context of JavaScript, such as picture clips, video clips, and 3D games. wait.

According to the definition of MDN, WebAssembly is a new type of code that runs in modern web browsers and provides new performance characteristics and effects. Can run in modern web browsers - it is a low-level assembly-like language with a compact binary format that can run at near-native performance and provides a compilation target for languages ​​such as C/C++ so that they Can run on the web. It was also designed to co-exist with JavaScript, allowing the two to work together.

3 How WebAssembly works

WebAssembly is not interpreted, but compiled into WebAssembly binary format by developers in advance, as shown in the figure below. Since the variable types are all predicted, the JavaScript engine does not need to monitor the code when the browser loads the WebAssembly file. It can simply compile the binary form of this code into machine code.

It would be inefficient to compile each programming language directly to its own version of machine code. The part of the compiler called the front end compiles the code you write into an intermediate representation (IR). After the IR code is created, the backend part of the compiler takes the IR code, optimizes it, and converts it to the required machine code.

Since browsers can run on several different processors (such as desktop computers, smartphones, and tablet devices), it would be cumbersome to distribute a compiled version of WebAssembly code for each possible processor. The alternative is to take the IR code and run it through a special compiler that converts the IR code into a special bytecode and puts it in a file with the .wasm extension. At this time, the bytecode in the wasm file is not machine code, it is just a set of virtual instructions that browsers that support WebAssembly can understand. When loaded into a browser that supports WebAssembly, the browser will verify the legality of this file, and then these bytecodes will continue to be compiled into machine code on the device on which the browser is running. As shown below

WebAssembly is designed to be a component of JavaScript, not a replacement for it. While some developers try to create entire websites using only WebAssembly, this is not the case universally. In general JavaScript is still the better choice.

4 Inside a WebAssembly module

Explanation of the meaning of different sections in the module:

The compiler is responsible for generating the segments of a WebAssembly module and placing them in the proper order.

All sections are optional, so empty modules may exist.

If known segments are specified, they must appear only once and in a specific order.

Custom sections can be placed before, between, or after known sections to specify data that does not apply to known sections.

5 Which languages ​​can be used to create WebAssembly modules?

Now the minimum viable version (Minimum Viable Product, MVP) of WebAssembly does not have garbage collection (garbage collection, GC), which limits the use of some languages. GC is being developed as a post-MVP feature, and ahead of implementation, several languages ​​are experimenting with WebAssembly support by compiling their own VMs to WebAssembly, or in some cases including their own garbage collectors.

The following languages ​​are experimenting with or have completed WebAssembly support:

  • C and C++
  • Rust is working to become the programming language of choice for WebAssembly.
  • AssemblyScript is a new compiler that converts TypeScript to WebAssembly.
  • TeaVM, a tool that translates Java to JavaScript, can now also generate WebAssembly.
  • Go 1.11 added an experimental project for WebAssembly that compiles WebAssembly modules to include a garbage collector.
  • Pyodide is a Python project that includes the core packages of the Python scientific stack: Numpy, Pandas, and matplotlib.
  • Blazor is Microsoft's experimental project for bringing C# to WebAssembly.

More lists follow github: WebAssembly support list

Related cases:

TeaVM: It translates JVM bytecode into JavaScript and WebAssembly

We have started to do some front-end development on the back end for a while, but the results are sometimes unsatisfactory. The key is that our back-end developers do not know much about the front-end framework, syntax, or specifications. This is inevitable, but it has to be done because of business needs.

TeaVM provides a solution for our situation, and our back-end developers still use their familiar language (java) for development. After the function development is completed, the _.class or _.jar file is compiled into wasm or JavaScript through TeaVM for the browser to load and call.

git:https://github.com/konsoletyper/teavm

Official website: https://teavm.org/

6 Where can WebAssembly be used?

Most browser vendors currently support WebAssembly, including Chrome, Edge, Firefox, and Safari. Mobile web browsers are also supported. Node.js is also supported since version 8.

WebAssembly is not a substitute for JavaScript, but a supplement to it. In some cases, WebAssembly is a better choice, and in some cases, using JavaScript will be a better solution. Running in the same VM as JavaScript allows the two technologies to complement each other.

WebAssembly provides a new path for non-JavaScript developers to help them use their own code in the web. It also gives web developers who don't know languages ​​like C or C++ access to newer, faster libraries. Personally understand that WebAssembly can also be used to optimize the execution speed of certain libraries.

6.1 Some use cases of webAssembly

Figma — a browser-based multi-person real-time collaborative UI design tool: https://www.figma.com/

Google Earth https://earth.google.com/ - Since 2017, it supports opening in FireFox, mainly relying on webAssembly. The previous use of Native Client resulted in only running in chrome

Magnum — Cross-platform OpenGL graphics engine https://github.com/mosra/magnum

Egret Engine - an HTML5 game engine https://github.com/egret-labs/egret-core/

Web-DSP — Create multimedia audio and video effects in real time using a browser https://github.com/shamadee/web-dsp

7 How to use WebAssembly?

7.1 Get the wasm file and import it manually

var importObject = {
  imports: {
      imported_func: function(arg) {
        console.log(arg);
      }
    }
  };
  // 输出 42
  fetch('simple.wasm')
  .then(res =>
    res.arrayBuffer()
  ).then(bytes =>
    WebAssembly.instantiate(bytes, importObject)
  ).then(results => {
    results.instance.exports.exported_func();
  });

7.2 Get the compiled npm package to import and execute

// alert(`Hello, ${name}`)
const js = import("./node_modules/@jdl/hello-wasm/hello_wasm.js");
js.then(js => {
  js.greet("WebAssembly");
});

The following is the source code of the hello_wasm.js file before compilation

// rust
extern crate wasm_bindgen;

use wasm_bindgen::prelude::*;

#[wasm_bindgen]
extern {
    pub fn alert(s: &str);
}

#[wasm_bindgen]
pub fn greet(name: &str) {
    alert(&format!("Hello, {}!", name));
}

This article provides a brief introduction to webAssembly in terms of why you need it, how it works, which languages ​​you can use to create WebAssembly modules, where and how it can be used. If you haven't learned about webAssembly before, you can do some brief understanding.

references

WebAssembly in Action - C. Gerard Gallant

Compiling Rust to WebAssembly - WebAssembly | MDN

Author: JD Logistics Pan Weigao

Source: JD Cloud developer community Ziqishuo Tech

Musk announced that Twitter will change its name to X and replace the Logo . React core developer Dan Abramov announced his resignation from Meta Clarification about MyBatis-Flex plagiarizing MyBatis-Plus OpenAI officially launched the Android version of ChatGPT ChatGPT for Android will be launched next week, now Started pre-registration Arc browser officially released 1.0, claiming to be a replacement for Chrome Musk "purchased for zero yuan", robbed @x Twitter account VS Code optimized name obfuscation compression, reduced built-in JS by 20%! Bun 0.7, a new high-speed JavaScript runtime , was officially released
{{o.name}}
{{m.name}}

Guess you like

Origin my.oschina.net/u/4090830/blog/10091194