Performance — Rust vs Web assembly Link to heading

Today, let’s compare performance difference of running a native executable compiled from Rust vs web assembly. As an example, we will run gzip decompression binary file compiled from native Rust code vs web assembly system interface (WASI), compiled from the same Rust code. WASI is an effort to standardize an interface to run web-assembly on any platform. See here for more details. Currently, WASI is still in an infant stage at Preview 1, and Preview 2 is in development. Even so, this works well for a simple project, like gzip decompression.

First, let’s clone a gunzip implementation in pure safe Rust.

git clone [email protected]:TechHara/gunzip.git
cd gunzip

This project creates a single executable gunzip that takes a .gz compressed stream from stdin and outputs decompressed stream out to stdout. To build and run it natively, we could do

# compile into exectuable that runs natively on the system
cargo build -r

# run and measure its runtime
time target/release/gunzip < /path/to//compressed.gz > decompressed

Now, to compile the same program into WASI, we first need to add the new target

rustup target add wasm32-wasi

Now, we can compile into WASI target without any code change at all!

# compile into WASI exectuable
cargo build -r --target wasm32-wasi

This will create a target/wasm32-wasi/release/gunzip.wasm file. To run this, we need a web assembly runtime that supports WASI. On macOS, one can install wasmtimer with brew

brew install wasmtime

Now, we can execute our WASI-compiled gunzip!

wasmtime target/wasm32-wasi/release/gunzip.wasm < /path/to/compressed.gz > decompressed.gz

I tested with linux kernel tar.gz file on a Macbook. With the native executable, it ran in 4.7s and 3.5s for total and user time, respectively. With WASI, it ran in 12.4s and 7.0s for total and user time, respectively. Looking at only the user runtime, WASI runs about 2x slower than native, which is quite impressive, considering that Python typically runs 100x slower than native.

Given that web assembly is less than 10 years old, I expect it to catch up in its performance even more so in the future. Unfortunately, threads are not supported in web assembly just yet, but hopefully it will be there in a few years down the road. Overall, WASI has bright future!