Wasm status quo

  • At present, it is mainly used in applications with high performance requirements, VR, games, etc
  • From the front-end perspective, it is not widely used, but major manufacturers are more positive about WASM and believe that wASM will be widely used in the near future.
    • Therefore, it is very important to learn a back-end language, C/C++/ Go/Python, it is recommended to learn Python or Go, Python is easier to get started than other languages, but I prefer go, I don’t want to do front-end to do back-end ~
  • Wasm experience

Wasm characteristics

  • standard
    • Webassemblies are designed to be versionless, feature testable, backward compatible on the Web,
    • Wasm can be called by JS, into the JS context, and can also invoke browser functions like a Web API
    • Wasm can be run in a browser or a non-Web environment
  • efficient
    • WebAssembly has a complete set of semantics, and WASM is a small, fast loading binary format that aims to harness the power of hardware to achieve native execution efficiency
  • security
    • Wasm runs in a sandboxed execution environment and can even be implemented in existing JS virtual machines
    • In a Web environment, WASM strictly adheres to the same origin policy and browser security policy
  • open
    • Wasm has designed a very neat text format in which you can view the source code of the WASM module on a Web page

Wasm runs as a module on the Web (wASM is implemented in the V8 engine) or on the server

wasm vs js

  • Wasm brings Parse forward during development
  • Wasm has no GC, and wASM GC is not the same thing as V8 GC in that it has a separate memory space that is managed by code, so be aware of memory issues in development

Performance issues

For example: recursive Fibonacci functions, WASM vs JS

Wasm development tools

Environment to prepare

  • Install the GCC compilation environment
  • Install g++ compilation environment
  • Install xcode
  • Install cmake
  • Emscripten: The soul of WASM, compiling other high-level languages into WASM for back-end languages
  • AssemblyScript: Supports compiling Typescript directly into WASM. Similar to TS syntax, but not typescript and not recommended (optional)
  • WABT: a tool for converting WASM between bytecode and text formats to facilitate understanding of the underlying WASM (optional) during development

Javascript API

  • methods

Compile wASM into code that v8 can execute — webassembly.instantiate () — webassembly.validate () to include WASM Whether a typed array of binary codes is valid

  • class
    • WebAssembly. The Module Module
    • WebAssembly. Examples of the Instance
    • Webassembly. Memory Memory space
    • Webassembly. Table is a JavaScript wrapper object – an array-like structure that represents a WebAssembly Table that stores function references. Tables created by JavaScript or WebAssembly code will be accessible from JavaScript and WebAssembly and mutable
    • WebAssembly.CompileError A compile time error
    • WebAssembly.LinkError instantiation error
    • Webassembly. RuntimeError RuntimeError

C wasm

Implement a Hello World

C -o hello * Execute executable program *./hello * output hello world! * /

/** * compile to wasm * emcc hello.c -o hello.js, generate hello.js and hello.wasm * Execute wasm * node hello.js * output hello world! * /

#include <stdio.h> // Introduce the standard input/output library

int main(a)
{
  printf("hello world! \n");
  return 0;
}
Copy the code

Generate WASM that runs in a browser

Math.wasm * emcc math.c -os -s wasm =1 -s SIDE_MODULE=1 -o math.wasm */

int add(int x, int y)
{
  return x + y;
}

int square(int x)
{
  return x * x;
}
Copy the code

Create the index.html page to invoke the WASM object in the browser

<! DOCTYPEhtml>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>
  <script>
    / * * *@param {String} Path WASM file path *@param {Object} Imports are passed to the variable */ in the WASM code
    function loadWebAssembly(path, imports = {}) {
      return fetch(path) // Load the file
        .then(response= > response.arrayBuffer()) / / to ArrayBuffer
        .then(buffer= > WebAssembly.compile(buffer))
        .then(module= > {
          imports.env = imports.env || {}

          // Open up memory space
          imports.env.memoryBase = imports.env.memoryBase || 0
          if(! imports.env.memory) { imports.env.memory =new WebAssembly.Memory({ initial: 256})}// Create a variable mapping table
          imports.env.tableBase = imports.env.tableBase || 0
          if(! imports.env.table) {// In the MVP version element can only be "anyfunc"
            imports.env.table = new WebAssembly.Table({ initial: 0.element: 'anyfunc'})}// Create a WebAssembly instance
          return new WebAssembly.Instance(module, imports)
        })
    }
    / / call
    loadWebAssembly('./math.wasm')
      .then(instance= > {
        const add = instance.exports.add // get the method in c
        const square = instance.exports.square // get the method in c

        console.log(10 + 20 '=', add(10.20))
        console.log('3 * 3 =', square(3))
        console.log('(2 + 5) * 2 =', square(add(2 + 5)))})</script>
</body>

</html>
Copy the code

Console output:

Join us at ❤️

Bytedance Xinfoli team

Nice Leader: Senior technical expert, well-known gold digger columnist, founder of Flutter Chinese community, founder of Flutter Chinese community open source project, well-known developer of Github community, author of dio, FLY, dsBridge and other well-known open source projects

We look forward to your joining us to change our lives with technology!!

Recruitment link: job.toutiao.com/s/JHjRX8B