Member-only story
How Fast is WebAssembly Versus JavaScript?
Conducting some simple benchmarks produced some surprising results
A few days ago, I wanted to have a go at building a website that was entirely powered on the frontend by WebAssembly. The easiest way of doing that today, in my opinion, is using Microsoft’s Blazor. In essence, you can write C# code where you’d previously use JavaScript, and Blazor will compile that C# to WebAssembly to allow it to run in the browser.
However, I was a little surprised to find that when I tested the speed of it versus the application written in JavaScript, it was noticeably slower. Therefore, I decided to benchmark WebAssembly to see how it performs versus JavaScript in a real-world scenario, such as a WebAssembly module being called from JavaScript.
What Is WebAssembly?
Before we dive into the benchmarking, some of you may not be familiar with WebAssembly, so I’m going to quickly cover what it is. If you’re already familiar, feel free to skip to the next section.
WebAssembly is a low-level assembly language that can run in any major browser. It’s designed to be fast, much faster than JavaScript, in order to handle the modern use cases of the web that require higher performance. Unlike JavaScript, that uses a just-in-time compiler at runtime, WebAssembly is compiled at build time and simply executed by the browser, in the same way Java is compiled at build time.
Engineers don’t typically write WebAssembly though, instead you write code as you would today in your preferred programming language, and then compile it to WebAssembly.
Several of the major languages are already supported, including C#, C/C++, Rust and TypeScript — with many other languages currently working on being production-ready.
WebAssembly can’t currently access the DOM, so it must rely on calling JavaScript to render any output from WebAssembly modules.
Is WebAssembly Faster Than JavaScript?
Compiling C# to WebAssembly is actually only possible with Blazor, so it’s not very useful for benchmarking. Instead, I’m going to use TypeScript (technically, AssemblyScript) that can be compiled easily…