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

边栏推荐
- Those confusing user state & kernel state
- ROS2前置基础教程 | 小鱼教你用CMake依赖查找流程
- Ros2 pre basic tutorial | using cmakelists Txt compile ros2 node
- flutter video_player实现监听和自动播放下一首歌曲
- 那些令人懵逼的用户态&内核态
- Recommendation of individual visa free payment scheme
- KEIL仿真和vspd
- DevSecOps: CI/CD 流水线安全的最佳实践
- 多年亿级流量下的高并发经验总结,都毫无保留地写在了这本书中
- 专业“搬砖”老司机总结的 12 条 SQL 优化方案,非常实用!
猜你喜欢

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

得物App数据模拟平台的探索和实践

Sdvo:ldso+ semantics, direct French Slam (RAL 2022)

keil MDK 中使用虚拟串口调试串口

NF-ResNet:去掉BN归一化,值得细读的网络信号分析 | ICLR 2021
![[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

DevSecOps: CI/CD 流水线安全的最佳实践

Self inspection is recommended! The transaction caused by MySQL driver bug is not rolled back. Maybe you are facing this risk!

Using virtual serial port to debug serial port in keil MDK
![Found several packages [runtime, main] in ‘/usr/local/Cellar/go/1.18/libexec/src/runtime;](/img/75/d2ad171d49611a6578faf2d390af29.jpg)
Found several packages [runtime, main] in ‘/usr/local/Cellar/go/1.18/libexec/src/runtime;
随机推荐
【直播回顾】战码先锋第六期:共建测试子系统,赋能开发者提
基础版现在SQL分析查询不能用了吗?
Reconstruction practice of complex C-end project of acquisition technology
Yilian technology rushes to Shenzhen Stock Exchange: annual revenue of RMB 1.4 billion, 65% of which comes from Ningde times
The summary of high concurrency experience under the billion level traffic for many years is written in this book without reservation
数据资产管理:数据发现,发现什么,怎么发现?
加密市场进入寒冬,是“天灾”还是“人祸”?
ROS2前置基础教程 | 使用CMakeLists.txt编译ROS2节点
大佬们 2.2.1cdc 监控sqlsever 只能拿到全量的数据 后期增量的数据拿不到 咋回事啊
推荐几个AI智能平台
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!
Recommendation of individual visa free payment scheme
“软件定义世界,开源共筑未来” 2022开放原子全球开源峰会7月底即将开启
Live broadcast goes to sea | domestic live broadcast room produces explosive products again. How can "roll out" win the world
【浙江大学】考研初试复试资料分享
Charles 乱码问题解决
个人免签支付方案推荐
At 19:00 this Thursday evening, the 7th live broadcast of battle code Pioneer - how third-party application developers contribute to open source
网络安全的五大特点有哪些?五大属性是什么?
大佬们好,初次使用MySQL cdc 报错