Going from JavaScript to WebAssembly in three steps

Click for: original source

It is vital that the performance on the client’s browser is as good as possible. The reason for this is very simple: when you are being told a story, or watching a movie, even a single frameskip immediately takes you out of your experience. By Marcel Duin.

WebAssembly (Wasm) is the ability for your browser to run compiled code at (near-) native speeds. It is now recognised by the W3C as the 4th official web programming language, after HTML, CSS and JavaScript.

With it, you can run compiled code written in a variety of programming languages (C/C++, Rust, Go, AssemblyScript, and many more) in your browser, without any need for plugins.

I was very impressed by a synth demo written in AssemblyScript, a language created specifically for WebAssembly, using the TypeScript syntax. Basically you can write (near) TypeScript, which compiles to a .wasm-binary. So anyone familiar with either TypeScript or JavaScript ES6 will not have a lot of difficulties using it.

This article describes my journey from upgrading the Micrio JavaScript-only client to use WebAssembly, with the hopes of improving performance, and taking my code to the next level:

  • The current version
  • First rewrite: C++ and emscripten
    • Coding C++ felt old-fashioned
    • The compiled .wasm binary was very large
    • TIL: A glue file
  • Second rewrite: AssemblyScript
    • Going atomic
    • Bundling the compiled Wasm inside the JS file
    • Realisation
  • Third Rewrite: AssemblyScript + WebGL
    • Moving the image tile logic to AssemblyScript
    • Connecting it to JavaScript
    • Rendering the lot

… and much more. The new client already felt a lot smoother in my browser. Zooming, panning and animating clearly went more smoothly than the previous JS-only version. It all resulted in 65% less CPU used than and there was less memory used. These results were also the same over multiple runs. Very insightful!

[Read More]

Tags javascript web-development browsers performance