The Rusty Web

Targeting the web with Rust.


This project demonstrates a complete, albeit simple, example of integrating Rust code into a web application. This is accomplished by compiling Rust to asm.js or WebAssembly. The basic design pattern this project explores uses Rust to implement CPU bound portions of an app while using existing web technologies to handle user facing, I/O bound pieces. The guide explores this design pattern in detail.

The demo compares implementations of the k-means clustering algorithm (this example's CPU bound task) applied to an image. The algorithm gives the resulting image a softened, painted look. Setting the k parameter controls the number of colors and the steps parameter controls the algorithm's number of iterations. After running the demo a few times, see the results section to compare runtimes.

Whereas this project looks at runtime performance, there are other benefits this design pattern offers: reducing website asset size, reducing JavaScript "compile" times, and the ability to use Rust!

Note: The demo may lock up the page. This is especially true on mobile devices. Consider uploading a smaller image and keeping the k and steps parameters small. In a real application, the task would either need to be broken into smaller pieces or run in a background thread using Web Workers.




Painter k Steps Size (pixels) Total (ms) Average (ms) Median (ms) Min (ms) Max (ms)
No results yet. Run the demo to add results.


The benchmarks show the average step duration computed for ten steps with k values ranging from two to sixty-four (smaller values are better). I tried to keep the implementations of the algorithm as similar, yet idiomatic, as possible to present a fair comparison, and attempted to compile with as many optimizations as possible. All targets were compiled using the rustc 1.17.0-nightly (b1e31766d 2017-03-03) version of the Rust compiler and the Emscripten toolchain version 1.37.3.

k=2 (ms) k=4 (ms) k=8 (ms) k=16 (ms) k=32 (ms) k=64 (ms)
Chromium 59 JavaScript 190 224 369 915 1935 3653
Firefox 55 JavaScript 99 136 217 382 683 1282
Chromium 59 Rust (asmjs) 125 126 154 181 293 511
Firefox 55 Rust (asmjs) 126 128 140 189 291 488
Firefox 55 Rust (wasm) 122 131 148 179 233 329
Chromium 59 Rust (asmjs) 61 76 95 121 182 320
Native Rust 19 25 35 54 90 155

Overall, I think the results are pretty promising. For the WebAssmebly version when k equals sixty-four, we are looking at a 4.0x speedup compared to the fastest JavaScript version with only a 2.0x slow down compared to native performance.

Note: These results are drastically different than my original findings which painted a pretty bleak picture for performance. Thanks to shurcooL for suggesting the fix. The fix was as simple as using multiplication to square a number instead of using powi. Just goes to show how deceiving benchmarks can be!