What is WebAssembly

WebAssembly (abbreviated Wasm) is a binary instruction format for a stack-based virtual machine. Wasm is designed as a portable compilation target for programming languages, enabling deployment on the web for client and server applications.

– webassembly.org/

Wasm is based on the binary instruction format of the stack virtual machine. As the compilation target of high-level programming language, it has strong portability and allows client and server applications to be deployed on the Web.

The background

JavaScript defects

Let’s take a look at how JavaScript code works in V8 [1].

  • JavaScript goes to the Parser, and the Parser turns it into an AST.
  • Based on the abstract syntax tree, Interpreter generates the bytecodes that the engine can read and execute directly
  • Next, the Compiler translates the bytecode line by line into Machine Code that can be executed efficiently.
  • For functions that have been executed many times, the engine compiles them into Machine Code and JIT optimizes them. The next Time the function is executed, the compiled Machine Code is executed directly.

Unlike strongly typed languages like C++ and JAVA, JavaScript is a weakly typed language that needs to be compiled dynamically at run time. A JS variable may be a Number one second and an Array the next, and this flexibility limits the optimization of the code in the engine.

asm.js

Given the inherent defects of JavaScript due to weak typing, can you optimize code performance by writing it specifically with implicit type inference? With this in mind, WebAssembly’s predecessor, asm.js, appeared.

For example, in the following code, | 0 causes the engine to infer that the variable A is an integer.

let a = 1.2 | 0
console.log(a) / / 1
Copy the code

However, asm.js does not solve all problems:

  • Asm. js is a strict subset of JavaScript, and developers cannot use all the features of JS;
  • Asm. js also exists as a compilation target (Emscripten can compile C++/C to asm.js), although the syntax is much clearer than WebAssembly, it is still difficult to write by hand.
  • Moreover, no matter how well asm.js does with the problem of type derivation, it always goes through the steps of Parser and Interpreter, which are the two most time-consuming steps in the engine execution of JS code.

WebAssembly appear

Given the problems with asm.js, WebAssembly skipped the Parser and Interpreter steps and ran directly in the browser as compiled bytecode (also compiled via Emscripten), greatly improving the speed of the code running in the browser. Here is a schematic.

In addition to speed, Wasm has the following advantages:

  • The unique binary format effectively reduces the package size and further improves the loading speed of the browser.
  • Support for compiling 10+ programming languages (C/C++, Rust, Go, etc.) into Wasm, which means you can borrow from the ecology of other languages and make standard libraries from other languages available directly in browsers.
  • Secure sandbox operating environment, in the browser also support same-origin policy and other permission restrictions;
  • Every major browser vendor (Firefox, Chrome, Safari, Edge, etc.) supports WebAssembly and continues to improve the standard. Today, WebAssembly has become the fourth Web language after HTML, CSS, and JavaScript.

Field demonstration

A brief description of how the Wasm program works:

  1. Write programs in other languages (C/C++, Rust, Go, etc.) and compile them into WebAssembly files (.wasm format) via their respective toolchains;
  2. Fetch, XMLHttpRequest and other. Wasm files, get a string of ArrayBuffer;
  3. Compile and instantiate ArrayBuffer as a browser-executable module;
  4. Call the method exported from within the Wasm module to complete the required operation.

Here’s a practical example:

Environmental installation

  • Git: used to pull emSDKs, etc
  • CMake: builds the C language
  • Host System Compiler: Linux-gcc, OSX-XCode, and WIN-VS Code
  • Python 2.7 +
  • Emscripten SDK: Wasm compiler
git clone https://github.com/juj/emsdk.git cd emsdk ./emsdk.bat install latest ./emsdk.bat activate latest ./emsdk_env.bat // To configure environment variables, run this command each time you log in again or create a shell windowCopy the code

Emscripten compiles C files

int multiply(int a,int b){
    return a * b;
}
Copy the code

Run emcc index.c -os -s WASM=1 -s SIDE_MODULE=1 -o Math. WASM to generate Math. WASM.

Load the call

<html>
<head>
  <script>
    // Check for wasm support.
    if(! ('WebAssembly' in window)) {
      alert('you need a browser with wasm support enabled :(');
    }

    function loadWebAssembly(filename, imports = {}) {
      return fetch(filename)
        .then(response= > response.arrayBuffer())
        .then(buffer= > {
          imports.env = imports.env || {}
          Object.assign(imports.env, {
            memoryBase: 0.tableBase: 0.__memory_base: 0.__table_base: 0.memory: new WebAssembly.Memory({ initial: 256.maximum: 256 }),
            table: new WebAssembly.Table({ initial: 0.maximum: 0.element: 'anyfunc'})})return WebAssembly.instantiate(buffer, imports)
        })
        .then(result= > result.instance)
    }

    loadWebAssembly('math.wasm')
      .then(instance= > {
        const { multiply } = instance.exports
        var button = document.getElementById('run');
        button.value = 'Call wasm multiply';
        button.addEventListener('click'.function() {
          alert('60 * 11 = ' + multiply(60.11))},false);
      })
  </script>
</head>
<body>
  <input type="button" id="run" value="waiting for WebAssembly..."/>
</body>
</html>
Copy the code

Using HTTP-server to start a static resource server locally and access the page, you can see that after clicking the button, the popup window displays 660, indicating that we successfully called the C file method in JS.

Application scenarios

Currently, Wasm has the following application scenarios:

1 performance

For computation-intensive or performance-intensive scenarios, such as image/video decoding, image processing, 3D/WebVR/AR, Wasm has obvious advantages. Such as:

  • Bilibili: While your video is still online, you can already choose the cover that the AI recommends. Here is the front end integration of WebAssembly +AI. Wasm is responsible for reading local videos and generating pictures. Tensorflow.js is responsible for loading the AI-trained model, reading the images and scoring them.
  • Figma: A browser-based collaborative UI design tool similar to Sketch.

2 reuse

Wasm compiles multiple high-level languages into binary code, making it possible to reuse the ecology of other languages in the browser. Such as:

  • Wasm version of the Unity Tutorial game: webassembly.org.cn/demo/
  • Using the OpenCV library to implement the browser real-time image capture and image processing: vinissimus. Making. IO/OpenCV – js – w…

3 a cross-platform

With the emergence of WASI (WebAssembly System Interface), WebAssembly can also be applied in non-browser environment, which gives more imagination space to the large-scale landing of Serverless [4].

Current situation of the development of

Development of language

The most popular Wasm languages are Rust, C++, AssemblyScript, etc. AssemblyScript is a TS language designed for Wasm to help front-end developers get started.

The application type

At present, WebAssembly applications mainly focus on Web application development, but the specific types of Web applications need to be investigated. In addition, there are many applications in game development, Serverless applications, containerization, audio and video processing, IoT, etc.

reference

  • [1] How browsers work: Chrome V8 makes you more JavaScript savvy
  • [2] The Complete Introduction to WebAssembly – Learn about The past and present of WASM
  • [3] webassembly.org/
  • [4] Serverless Days 2020 Looks at Future of Serverless Architecture
  • [5] The State of WebAssembly 2021

The last

Check out our official Eval Studio account to follow us for more updates