当前位置:网站首页>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 C、C++ and Rust( That is, because they manage memory themselves and do not need a garbage collector ). Yes Go、Python 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 initContinue execution after initialization :
npm install --save-dev assemblyscriptAfter 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 startYou 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 :

边栏推荐
- PowerPoint tutorial, how to add watermarks in PowerPoint?
- Good wind relies on strength – code conversion practice of accelerating SQL Server Migration with babelfish
- 2022年失业的人多吗?今年是不是特别难找工作?
- ROS2前置基础教程 | 小鱼教你用CMake依赖查找流程
- mysql如何将字段修改为not null
- Database connection pool: implementation of connection pool function point
- 那些没考上大学的人,后来过的怎样
- DevSecOps: CI/CD 流水线安全的最佳实践
- Follow up to the "June 21" gas explosion accident in Tai'an, Shandong Province: comprehensive investigation and remediation of potential gas safety hazards in restaurants
- 时隔17年,刘亦菲再次刷屏式爆红:普通人不想被淘汰,也要懂得这件事
猜你喜欢

华为机器学习服务银行卡识别功能,一键实现银行卡识别与绑定

PowerPoint tutorial, how to add watermarks in PowerPoint?

ROS2前置基础教程 | 小鱼教你用CMake依赖查找流程
![[graduation project] Research on emotion analysis based on semi supervised learning and integrated learning](/img/02/33d7b6a5bc01737c5dbeb944202a66.jpg)
[graduation project] Research on emotion analysis based on semi supervised learning and integrated learning

New hybrid architecture iformer! Flexible migration of convolution and maximum pooling to transformer

模板特例化 template<>

Zhongshanshan: engineers after being blasted will take off | ONEFLOW u

曾经,我同时兼职5份工作,只为给女友买个新款耳环......

Driving the efficient growth of the manufacturing industry, UFIDA u9 cloud is constantly improving the password behind it

极致效率,云原生数据库TDSQL-C安身立命的根本
随机推荐
关于 GIN 的路由树
PHP built-in protocols (supported and encapsulated protocols)
得物App数据模拟平台的探索和实践
How to open an account in flush? Is online account opening safe?
[graduation project] Research on emotion analysis based on semi supervised learning and integrated learning
U++ operator learning notes
【浙江大学】考研初试复试资料分享
At 19:00 this Thursday evening, the 7th live broadcast of battle code Pioneer - how third-party application developers contribute to open source
Charles 乱码问题解决
FPGA采集DHT11温湿度
【题目精刷】2023禾赛-FPGA
Reading of double pointer instrument panel (II) - Identification of dial position
Bochs software usage record
Hello, big guys. Error reporting when using MySQL CDC for the first time
求求了,别被洗脑了,这才是90%中国人的生存实况
Reconstruction practice of complex C-end project of acquisition technology
KEIL仿真和vspd
Go all out to implement the flood control and disaster relief measures in detail and in place, and resolutely protect the safety of people's lives and property
PHP内置协议(支持的协议和封装协议)
2022年失业的人多吗?今年是不是特别难找工作?