What is webassembly
Before December 2019, if you want to write a web page, it must be inseparable from the three good brothers of html, css, and js. After December 2019, W3C announced that webassembly had joined them. Why join webassembly after the three brothers? Is it different from the previous one? Taking js as a comparison, let's take a look at their differences in detail.
The difference between wasm and js
js is an interpreted language. It does not compile before the code runs, but compiles it in real time during execution. In order to enable smooth execution while compiling, we have a js engine.
Wasm is different. It is not a programming language, but a bytecode standard. Different kinds of high-level programming languages, such as Rust, Go, Python, etc., can be used to convert the code into The .wasm file is put into the wasm virtual machine pre-made in the browser to run.
At the same time, this feature, which is different from js and can be run in advance, also brings some advantages to wasm:
- has a complete set of semantics: wasm The complete semantics of this small and fast-loading binary format allows the hardware to give full play to its capabilities to achieve native execution efficiency.
- requires less time to compile and optimize: requires multiple compilations of code as a dynamic type compared to js. Wasm allows files to be optimized before they are pushed to the server, which can effectively reduce compilation and optimization time.
- executes faster: wasm is a binary file, its instructions are closer to machine code, and the execution speed is faster than js.
- garbage collection is more efficient: wasm currently does not support automatic garbage collection. Garbage collection is controlled manually, which is more efficient than automatic garbage collection.
Of course, if you just say that, we can't intuitively feel how big these advantages are. It just so happens that the current browser already supports the wasm-standard virtual machine.
Next, let's get a feel for it through an instance test of Chrome and Safari.
Comparison of wasm and js execution speed
First, we use native js to write a fib code test time, the code content is as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
function fibonacci(n) {
if (n == 0 || n == 1)
return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
function fibonacciTime() {
console.time("js")
fibonacci(40)
console.timeEnd("js")
}
fibonacciTime()
</script>
</body>
</html>
Test time with live-server, it took 1275 milliseconds to 1329 milliseconds.
Then we use Rust to escape to wasm and test again. particularly important to note that the algorithms used in the test are the most common recursive iterations. In actual use, we can also use dynamic programming to optimize again.
Closer to home, then we use the rust-wasm compiler to convert the fib code written in rust into a wasm file.
Download the wasm compiler:
curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh
Configure Cargo.toml:
[package]
name = "wasm"
version = "0.2.0"
authors = ["hzjsea"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
crate-type = ["cdylib"]
path = "src/main.rs"
[dependencies]
wasm-bindgen = "0.2.48"
chrono = "0.4.19"
main.rs:
use chrono::Utc;
use wasm_bindgen::prelude::*;
use std::time::Instant;
#[wasm_bindgen]
pub fn fib(n: i32) -> i32 {
match n {
0 => 1,
1 => 1,
_ => fib(n - 1) + fib(n - 2),
}
}
pub fn main(){
let result = fib(40);
println!("{:?}", result);
}
Mount the wasm file, which is similar to vue, use index.html to mount the wasm.js file:
<script type="module">
main()
async function main() {
const wasm = await import('/pkg/wasm.js')
await wasm.default('/pkg/wasm_bg.wasm')
console.time("rust")
console.log(wasm.fib(40))
console.timeEnd("rust")
}
function fibonacci(n) {
if(n==0 || n == 1)
return n;
return fibonacci(n-1) + fibonacci(n-2);
}
function fibonacciTime(){
console.time("js")
fibonacci(40)
console.timeEnd("js")
}
fibonacciTime()
</script>
Then use the compiler to compile the Rust code to generate a .wasm file:
wasm-pack build --target web --no-typescript --mode normal
Then we can clearly see that the time difference is about double under the same live-server test.
Because this compilation specifies not to generate the ts version of wasm. All only the above few files, of which:
- package.json
{
"name": "wasm",
"collaborators": [
"hzjsea"
],
"version": "0.2.0",
"files": [
"wasm_bg.wasm",
"wasm.js"
],
"module": "wasm.js",
"sideEffects": false
}
Specify the various attributes of the package
- wasm_bg.wasm
Binary file after wasm.js escaped
- wasm.js
The wasm.js file transferred from the rust code.
wasm's component library
After reading the example test, we cannot skip the Rust mentioned in the test. There is a framework similar to react in Rust called Yew. About Yew official [ https://github.com/yewstack/yew] description is as follows:
Yew is a modern Rust framework for creating multi-threaded front-end web apps with WebAssembly.
- Features a macro for declaring interactive HTML with Rust expressions. Developers who have experience using JSX in React should feel quite at home when using Yew.
- Achieves high performance by minimizing DOM API calls for each page render and by making it easy to offload processing to background web workers.
- Supports JavaScript interoperability, allowing developers to leverage NPM packages and integrate with existing JavaScript applications.
Timer
After reading Rust roughly, if you want to see more WebAssembly processes, an official timer training project can meet your needs
Project address https://yew.rs/docs/zh-CN/getting-started/build-a-sample-app
You can mainly look at the file lib.rs
Summary and reflection
Although webassembly is often mentioned as a new web technology, it is still in the process of resolving problems due to the difficulty of debugging the tool chain and the large package size. It also shows that wasm cannot be directly replaced in a short time. js, they are more of a complementary and cooperative relationship. But it is undeniable that projects suitable for webassembly scenarios will continue to appear in the future, and you can learn more about it.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。