当前位置:网站首页>Meet webassembly again

Meet webassembly again

2022-06-22 15:36:00 devpoint

WebAssembly (Wasm) Is based on the stack of virtual machine binary instruction format , A low-level assembly language , Designed to be very close to compiled machine code , And very close to the native performance . In the previous article 《 Get to know WebAssembly》 Introduced some , This article introduces its advantages and usage scenarios again , Experience through code WebAssembly The process of project development .

In short ,Wasm Is a compilation target , You can use about 30 Code written in languages , Use is specific to WebAssembly To compile it , Compile it to .wasm file , At present, the most popular target is Wasm My language is CC++ and Rust( That is, because they manage memory themselves and do not need a garbage collector ). Yes GoPython and JavaScript Ecosystem support is also growing rapidly . Compile generated .wasm The file can be in the browser or on the server .Wasm The file contains binary instructions that the virtual machine can read , And because of Wasm Target virtual machines , So it can be applied to many chip architectures , It aims at the smallest common denominator of popular hardware , Stack machine , This is what distinguishes it from other targets that generate binary code .

Wasm Originally built for browsers , But as technology matures , I see more and more use cases on the server side . This article introduces WebAssembly Advantages and application scenarios of , And know the process of project development through examples , Click on Look at the code .

What advantages do you have

Wasm Allow code to be written in a familiar language and run anywhere .

Faster startup time

On the server ,Wasm It can be achieved by Docker The container is fast 10-100 Times the cold start time , Because it doesn't need to create one for each container OS process . In the browser , decode Wasm Comparative analysis 、 Explain and optimize JavaScript faster , therefore Wasm The code executes faster in the browser than JavaScript faster .

Near native performance

About Wasm There are some controversies about the performance details of , But its advantage is that it allows users to encapsulate the compute intensive parts of their applications into lower level languages . Wasm Many of the performance advantages of the come from it ( It is Wasm Code ) The fact that is built as close to native machine code as possible .

Lightweight

Wasm Binary files are small , So only a small amount of bandwidth is used , It is usually better than cross compilation in browsers JavaScript Spend less time over the network .

Convenient and universal

whatever Wasm The runtime can run any Wasm Code ( Although not all runtimes support all Wasm Expand , That's different WASI Interface type ). Most browsers support WebAssembly, And on the server side (WasmEdge、Wasmtime etc. ) There are many running Wasm The runtime of the code . Whereas browsers and servers ( And the hardware ) Yes Wasm Broad support for , It is portable , And it is also very common , about 30 Languages can be compiled or executed in (C、C++、Rust、Python、Go、AssemblyScript、JavaScript wait ).

Security

WebAssembly The two goals of the security model are :(1) Protect users from errors and or malicious modules ;(2) Provide developers with the primitives they need to develop secure applications . To this extent ,Wasm The scope of is limited , stay Wasm The code that runs in the runtime is memory sandboxed and functionally limited .

The above points make it interesting for both client and server applications . On the client side , There is a world ( part ) because Wasm, The browser eventually becomes the default operating system for all applications . On the server ,Wasm It is possible to become the next default container system .Docker What you do with virtual machines ,Wasm It will be right Docker do . just as Fermyon Of Matt Butcher said :

if VM Is the heavyweight of cloud computing , The container is intermediate , that WebAssembly It is the perfect choice for lightweight .

Application scenarios

Wasm Will provide fast and secure client and server applications , What are the application scenarios ?

Speed up WEB Applications

according to Figma Use cases , Use Wasm, The performance of the application can be / The calculation intensive part uses JavaScript To write , And then JavaScript Switch to a higher performance language , for example Rust/C/C++. But that's not always the case .

Everything is (Web) Applications

Write once , Run anywhere ,WebAssembly Hope to achieve this initially by Sun Microsystems Creative and Java About the term dream . This is not a simple feat in practice , but Wasm It's definitely easier to bring an application to a previous native Web( And other platforms ) On .Photoshop and Autodesk Web That's a good example .

plug-in unit

Wasm Ideal for executing untrusted code in isolated sandboxes . Once most platforms are scaled , Eventually the plug-in system will be built , Enable end users to build custom software that interacts with their platforms . By using... In this plug-in system Wasm, The platform allows their users to build plug-ins in any language , Without worrying about the security risk of letting users execute untrusted code , Because the code is sandboxed .Wasm All the other benefits of are also at work here : Speed 、 Small binaries and fast loading . By default , Every plug-in system wants high performance 、 Safe and easy to use , and Wasm Helped achieve this goal .

New container system

As mentioned above ,Wasm With a constrained security model , It is cross operating system , With fast cold start time , Excellent performance , There is no need to create new operating system processes for each container , And it takes up very little space . These are all replaceable Docker Attractive features of the new container system . just as Solomon Hykes As tweeted ,WASI It is the missing link that really promotes the development of this new container system .

Package manager

WebAssembly There will be a package registry and manager .WAPM Was the first person to try this , once WASI And component models are everywhere , There will be many convincing reasons why Wasm Package manager .

game

In the browser ,WebAssembly Maybe it's great , The reason is that it is performance intensive Web Applications are very useful : Let them in Web Run efficiently on the Internet . according to WebAssembly file , Examples include lightweight games that require a quick start 、 Asset intensive AAA Games and point-to-point games . Same basis WebAssembly Document introduction , It can be used to create game distribution services on the server , Make the game portable and safe .

Blockchain

People have been talking about Wasm As EVM substitute ,Parity Ethereum Client stay Wasmi Run in Wasm Bytecode , This makes Wasm The code can access and interact with the blockchain . Another good example is ewasm, It is currently being studied as EVM1 substitute ( source ). It is designed for developers to use WebAssembly Interact with Ethereum blockchain , To support more languages .

Server side calculations for untrusted code

A use case similar to a plug-in system is server-side computation of untrusted code . Many platforms will eventually expose their systems , Let end users write code on their platform , for example Airtable Scripts. Use Wasm, image Airtable Such a platform allows its users to Airtable Scripting Write functions written in multiple languages on the platform .

Serverless computation

The serverless function is WebAssembly The perfect scene ,Wasm My sandbox 、 performance 、 Fast startup times and language support make it the perfect technology to run serverless functions .

machine learning

With the real-time work of the Internet of things / Connecting devices are becoming more and more popular , Being able to perform real-time machine learning will become critical . image WasmEdge Such a runtime makes this possible .

Hello World

This article will use AssemblyScript To build “Hello World” , Create project directory wasm-hello, Execute the order :

npm init

Continue execution after initialization :

npm install --save-dev assemblyscript

After installation , The compiler provides a convenient scaffolding utility to quickly set up a new project , In the current directory :

npx asinit .

asinit The command will automatically create the recommended directory structure and configuration file :

  • ./assembly : Store and compile as WebAssembly Of AssemblyScript Source directory .
  • ./assembly/tsconfig.json :TypeScript The configuration inherits the recommended AssemblyScript Set up .
  • ./assembly/index.ts : Project entry documents
  • ./builds: Build artifact Directory , Where the compiled WebAssembly file .
  • ./build/.gitignore
  • ./asconfig.json
  • ./package.json
  • ./tests/index.js
  • ./index.html

Next , Create a scripts To hold the JavaScript Code file for , create a file main.js , A use WebAssembly Web API load Wasm Function of module :

const wasmBrowserInstantiate = async (wasmModuleUrl, importObject) => {    let response = undefined;    if (!importObject) {        importObject = {            env: {                abort: () => console.log("Abort!"),            },        };    }    //  Check whether the browser supports stream instantiation     if (WebAssembly.instantiateStreaming) {        //  Get module , And instantiate it at download time         response = await WebAssembly.instantiateStreaming(            fetch(wasmModuleUrl),            importObject        );    } else {        const fetchAndInstantiateTask = async () => {            const wasmArrayBuffer = await fetch(wasmModuleUrl).then(                (response) => response.arrayBuffer()            );            return WebAssembly.instantiate(wasmArrayBuffer, importObject);        };        response = await fetchAndInstantiateTask();    }    return response;};

Next, use the above function to load the instantiation wasm modular , from Wasm The module calls the exported add() function :

const runWasm = async () => {    //  Instantiation wasm modular     const wasmModule = await wasmBrowserInstantiate("./build/core.wasm");    //  from wasm  call  add  function     const addResult = wasmModule.instance.exports.add(24, 24);    //  Add the result of function execution to  DOM in     document.getElementById(        "result"    ).innerHTML = `Hello World! addResult: ${addResult}`;};runWasm();

Go back to the project directory html file , The code is as follows :

<!DOCTYPE html><html lang="en">    <head>        <meta charset="UTF-8" />        <title>Hello World - AssemblyScript</title>    </head>    <body>        <div id="result">        </div>        <script src="./scripts/main.js"> </script>    </body></html>

Start the program :

npm start

You can see the effect , Note that the latest version should be upgraded node Environment to version 16 above .github The code on is a more complex example ( From the official ), The running effect is shown in the figure :

原网站

版权声明
本文为[devpoint]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206221409491760.html

随机推荐