当前位置:网站首页>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 :

边栏推荐
- Hongshi electric appliance rushes to the Growth Enterprise Market: the annual revenue is 600million yuan. Liujinxian's equity was frozen by Guangde small loan
- 还可以这样搞nlp(分类)
- 那些令人懵逼的用户态&内核态
- 数据资产管理:数据发现,发现什么,怎么发现?
- Token processing during API encapsulation
- 天安科技IPO被终止:曾拟募资3.5亿 复星与九鼎是股东
- ROS2前置基础教程 | 小鱼教你用CMake依赖查找流程
- 鸿世电器冲刺创业板:年营收6亿 刘金贤股权曾被广德小贷冻结
- New hybrid architecture iformer! Flexible migration of convolution and maximum pooling to transformer
- What are the five characteristics of network security? What are the five attributes?
猜你喜欢

模板特例化 template<>

KEIL仿真和vspd

HMS Core新闻行业解决方案:让技术加上人文的温度

【浙江大学】考研初试复试资料分享

No wonder the postgraduate entrance examination is so hot. These are the "hidden benefits" of Postgraduates!

极致效率,云原生数据库TDSQL-C安身立命的根本

得物技术复杂 C 端项目的重构实践

口令安全是什么意思?等保2.0政策中口令安全标准条款有哪些?

PHP built-in protocols (supported and encapsulated protocols)

基于最小化三维NDT距离的快速精确点云配准
随机推荐
基于最小化三维NDT距离的快速精确点云配准
时隔17年,刘亦菲再次刷屏式爆红:普通人不想被淘汰,也要懂得这件事
New hybrid architecture iformer! Flexible migration of convolution and maximum pooling to transformer
向量2(友元及拷贝构造)
Hello, big guys. Error reporting when using MySQL CDC for the first time
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
Flutter video Le lecteur écoute et joue automatiquement la prochaine chanson
visual studio开发过程中常见操作
I rely on the sideline to buy a house in full one year: the industry you despise will make a lot of money in the next ten years!
I took a private job and earned 15250. Is it still necessary to do my main business?
关于 GIN 的路由树
口令安全是什么意思?等保2.0政策中口令安全标准条款有哪些?
百行代码实现基于Redis的可靠延迟队列
"Forget to learn again" shell process control - 38. Introduction to while loop and until loop
数据库连接池:压力测试
网络安全的五大特点有哪些?五大属性是什么?
『忘了再学』Shell流程控制 — 38、while循环和until循环介绍
Those confusing user state & kernel state
Ask if you want to get the start of sqlserver_ Is there a good way for LSN?