What is a webassembly
Before December 2019, if you were going to write a Web page, you would need HTML, CSS, and JS. After December 2019, the W3C announced that WebAssembly had joined them. Why join WebAssembly after three brothers? How is it different from the previous one? With JS as a contrast, let’s look at the differences in detail.
Differences between WASM and JS
Js is an interpreted language, which does not compile code before it is run, but rather compile it in real time during execution. To make compilation and execution work, we have a JS engine.
Wasm, on the other hand, is not a programming language in itself, but a bytecode standard that can be converted into.wASM files by the compiler of various high-level programming languages such as Rust, Go, Python, etc., and run in the browser’s pre-made WASM virtual machine.
The fact that wASM can be pre-run, unlike JS, also gives wASM some advantages:
-
Have a complete set of semantics: WASM’s complete semantics in a small, fast loading binary format enable hardware to achieve native execution efficiency.
-
Less compile and optimize time: Compared to js being a dynamic type that requires multiple compilations of code, WASM allows files to be optimized before they are pushed to the server, reducing compile and optimize time significantly.
-
Faster execution: WASM is a binary file whose instructions are closer to machine code and can execute faster than JS.
-
More efficient garbage collection: WASM does not currently support automatic garbage collection, which is manually controlled and more efficient than automatic garbage collection.
Of course, it’s not obvious how big these advantages are, since browsers already support virtual machines with the WASM specification.
Let’s get a feel for this with a Chrome versus Safari test.
Compare wASM to 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>Copy the code
The time was tested with the live-server in the range of 1275 to 1329 milliseconds.
We then tested it again with Rust escape as WASM. In particular, it should be noted that the algorithms used in the test are the most common recursive iterations, and in practice we can also use dynamic programming to optimize again.
Without further ado, we then 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
Copy the code
Configuration Cargo. Toml:
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"Copy the code
The 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); }Copy the code
To mount the wASM file, use index.html to mount the wasm 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>
Copy the code
Then compile the Rust code with the compiler to generate.wasm files:
wasm-pack build --target web --no-typescript --mode normal
Copy the code
Then we can obviously see that the time difference is about double under the same live-server test.
This compilation specifies that a TS version of WASM is not generated. There are only a few files above, among which:
- package.json
{" name ":" wasm ", "collaborators" : [" hzjsea] ", "version" : "0.2.0," "files" : [" wasm_bg. Wasm ", "wasm. Js]", "the module" : "wasm.js", "sideEffects": false }Copy the code
Specify the various properties for packaging
- wasm_bg.wasm
Wasm.js escaped binary file
- wasm.js
The wasM.js file transferred from the rust code.
Wasm component library
Having looked at the sample tests, we cannot skip over Rust mentioned in the tests. Rust has a framework similar to React called Yew. About Yew Official [github.com/yewstack/ye…
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.
The timer
If you still want to see more of The WebAssembly process, Rust offers a hands-on timer program to meet your needs
Yew. Rs /docs/zh-CN/… yew.
Take a look at the lib.rs file
Summary and Reflection
Although WebAssembly is often mentioned as a new Web technology, it is still in the process of being solved because of the debugging difficulties of its tool chain and the large package size. Meanwhile, it also shows that WASM cannot directly replace JS in a short time, and they are more complementary and cooperative. However, there is no denying that projects that fit the WebAssembly scenario will continue to emerge for some time to come, so you can read more about them.
Recommended reading
Flink’s practice in cloud log batch processing
User IP. How many secrets are in there?