How fast Wasm can be?
Recently I started learning Rust. I love this language so much.
I recently did a little experiment with WebAssembly that Rust can produce. I want to know how efficient it can be as opposed to JavaScript.
So I created a function that calculates the Fibonacci sequence to measure the performance. It's a recursive function so must be CPU-intensive.
Here's each function.
// JS
function fibonacciJs(n) {
if (n < 2) {
return n;
}
return fibonacciJs(n - 1) + fibonacciJs(n - 2);
}
// Rust
pub fn fibonacci(n: i64) -> i64 {
if n < 2 {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
I built a pkg using the wasm-pack
library, then imported it into JS, bundled with Webpack.
import * as wasm from '../../../../pkg'
const t0 = performance.now()
const f1 = wasm.fibonacci(BigInt(10)).toString() // By using BigInt and toString method, wasm can be posed a bit of penalty.
const t1 = performance.now()
console.log(f1, (t1 - t0) / 1000) // seconds
Result: 55
// Wasm (Rust)
0.00019999998807907106
// JS
0 // technically, it shouldn't be 0, but the console doesn't print decimal numbers.
Both fast. There are practically no differences between them.
Result: 6765
// Wasm (Rust)
0.00019999998807907106
// JS
0.0017000000476837158
The results started showing the difference. JS took 0.00170 seconds, whereas Wasm took 0.00019.
Wasm is 8.5x faster.
Result: 832040
// Wasm (Rust)
0.006199999988079071
// JS
0.013400000035762787
Wasm is 2.16x faster.
Result: 102334155
// Wasm (Rust)
0.4855
// JS
0.9456000000238418
Still, Wasm is about 1.94x faster.
Result: 12586269025
// Wasm (Rust)
56.65560000002384
// JS
208.27239999997616
The calculation suddenly became intensive after around 43. Wasm took 56 seconds. JS took 208 seconds.
Wasm is 3.67x faster.
Result: 20365011074
// Wasm (Rust)
94.788
// JS
366.3071999999881
JS took 366 seconds which is 6 minutes! It took 94 seconds even for Wasm.
Wasm is 3.86x faster.
I think continuing more than 51 would be unrealistic. So I'm wrapping up here.
As I expected, Wasm is a lot faster than JS.
What surprised me most was that calculating the Fibonacci sequence recursively is a nasty job for computers. But interestingly, I ran these CPU-heavy calculations continuously, my MacBook M1 Pro (2021) stays cool during the entire test. Actually, I've never heard the fan noise at all since I bought it. Impressive.
😎