WebAssembly and Emscripten

Sebastiano Tronto

ALTEN Advanced Software Evening

Your browser runs code


+



var aInput = document.getElementById("aInput");
var bInput = document.getElementById("bInput");
var button = document.getElementById("resultButton");
var resultText = document.getElementById("resultText");

button.addEventListener("click", () => {
        var a = Number(aInput.value);
        var b = Number(bInput.value);
        resultText.innerText = a + b;
});

WebAssembly

WASM first appeared in 2017 as a more performant language for the browser.

It runs in a VM and can interact with JavaScript, but not with the DOM.

WebAssembly - code example


(func (param i64) (result i64)
  local.get 0
  i64.eqz
  if (result i64)
      i64.const 1
  else
      local.get 0
      local.get 0
      i64.const 1
      i64.sub
      call 0
      i64.mul
  end)

WebAssembly - code example


(func (param i64) (result i64)
  local.get 0
  i64.eqz
  if (result i64)
      i64.const 1
  else
      local.get 0
      local.get 0
      i64.const 1
      i64.sub
      call 0
      i64.mul
  end)
Same thing in Python:

def f(n):
    if n == 0:
        return 1
    else
        return n * f(n-1)

Emscripten

"Emscripten is a complete compiler toolchain to WebAssembly, using LLVM, with a special focus on speed, size, and the Web platform."

Hello, world!

  1. Write an Hello World program in C or C++
  2. Compile with
    emcc -o index.html hello.c
  3. Run a web server and open a browser!

Writing a library

Thanks Emscripten, we'll write our own HTML!
  • Goal: write a library with a function to sum two numbers, and use it in a simple web page
  • See examples/2-sum
  • Some extra options are needed:

emcc -sEXPORTED_FUNCTIONS=_sum \
     -sMODULARIZE \
     -sEXPORT_NAME=SumLibrary \
     -o sum_library.mjs \
     sum_library.c

Exercise: count prime numbers

Performance benchmark

Firefox
WASM (-O3)
Firefox
JS
Chromium
WASM (-O3)
Chromium
JS
1e7 Primes (iterative) 4.5s4.4s 4.7s4.6s
1e7 Primes (sieve) 0.76s0.82s 0.92s0.80s
Matrix multiplication 0.81s5.3s 1.5s4.6s

More exercises

See github.com/sebastianotronto/emscripten-tutorial

Drinks!