Google I/O '19: WebAssembly for Web Developers

Google I/O '19: WebAssembly for Web Developers

posted in javascript on


emscripten-core/emscripten : An LLVM-to-Web Compiler

Brings your existing C/C++ applications to the web (ex: Autocad, Game Engines like Unity). Provides a drop-in replacement: Whatever you wrote, it should just work on the web. It emulates OpenGL, the FileSystem etc.

For Web Developers

Two main use cases

  • Surgical replacement of tiny modules in your JavaScript, the hot paths, the bottlenecks, with WebAssembly
  • Use existing libraries that do not exist on npm from another ecosystem (C/C++, Rust, …)

The Performance Myth

WebAssembly and JavaScript both have the same peak performance. But… JavaScript can easily fall off the “fast path” while WebAssembly will not.

Inside V8
  • js input
    • Ignition: Interprets the JS text and runs it. While running, collects analytics data about how the code is behaving before TurboFan kicks in.
    • TurboFan: The optimizing compiler.
  • wasm input
    • Liftoff: The streaming WebAssembly compiler which generates machine code.
    • TurboFan: The optimizing compiler which generates optimized code.

With JavaScript input, TurboFan will deopt (deoptimization) when the assumptions from the collected analytics no longer hold true reverting back to the Ignition interpreter. With Liftoff you always stay on the fast path.

WebAssembly delivers more predictable performance than JavaScript

The peak performance is about the same but in some browsers the JavaScript performance is way off!

The Future

WebAssembly Threads and SIMD

Will allow WebAssembly to outperform JavaScript.

  • Shared Linear Memory
  • Atomic operations
  • Implemented with WebWorkers
  • Ships with Chrome 74

Host bindings

Interact easily with JavaScript and DOM objects with the Web IDL interface. Will also greatly reduce the glue overhead that is currently required.

Web IDL is a requirement for other proposals such as Garbage Collection, Tail Call optimizations and Exception Handling.

ECMA module integration

import {foo} from './myModule.wasm';

An Example

Windows Emscripten SDK Installation

Install the Emscripten SDK

git clone
cd emsdk
.\emsdk.ps1 install latest
.\emsdk.ps1 activate latest

An Application

Your original, mega complex C application HelloWorld.c

#include <stdio.h>

int main(int argc, char ** argv) {
    printf("Hello World\n");

Turning it into a wasm file:

emcc HelloWorld.c -s WASM=1 -o HelloWorld.html
npx http-server

Open the generated HelloWorld.html in a browser to see your WebAssembly file executed!

For this “program”, a 40kb HelloWorld.wasm file and 55kb of JavaScript glue in HelloWorld.js were generated.

Stuff that came into being during the making of this post
Other interesting reads
Tags: tech-talk