A Comprehensive Guide to Using WebAssembly
- August 17, 2020
- Liu, An-Chi 劉安齊
¶ 1. Introduction
Let’s start with the basics: what is WebAssembly, and why do we need it?
Today, web technology is everywhere. People spend hours online every day, enjoying all kinds of services. More and more applications are moving to the web, and desktop or mobile apps increasingly adopt web-based implementations (Web Apps) or hybrid architectures (Hybrid Apps). In a sense, web technology has taken over the world.
The web runs on JavaScript (JS). As browsers and JS engines have evolved, we seem to have reached a bottleneck for performance optimization. No matter how fast JS becomes, because it is an interpreted language, it reads and compiles code line by line at runtime. This execution model is inevitably slower than compiled languages such as C++.
Then you might ask: why not use compiled languages like C++ directly on the web? Because whether you compile ahead of time or compile in the browser, there are trade-offs. Ahead-of-time compilation typically produces large binaries; shipping those to the browser can waste network transfer time. If you ship source-like representations and compile in the browser, you may still pay a significant compile time before you can run. With JS, the source files are relatively small (so transfer is acceptable), and the browser can compile incrementally as it reads, so earlier compiled parts can start running sooner without making the experience unbearably slow.
Either way, JS performance has limits. People wanted a way to make web applications run faster in browsers, and that is where WebAssembly (WASM) comes in. WASM is a low-level, assembly-like format whose performance can approach native code—similar to what you get from C++ or Rust. In web development, JS and WASM are used together. The basic idea is: keep general application logic in JS, but move compute-heavy parts into precompiled WASM to significantly improve performance. This way, you get both fast startup (JS) and high performance for heavy computation (WASM).
Next, this post introduces how to develop using JS together with WASM.
Continue reading