Nazanin De's Blog

Projects, Ideas and thoughts

All about WebAssembly

WebAssembly or WASB is the new safe and portable, load-time efficient compact binary format to compile on the Web.

WebAssembly code is a structured stack machine, a machine where most of its operations use a stack of values but control flow is structured in blocks, loops, and etc.

What is so great about WebAssembly that it is being developed as a web standard by W3C Web Assembly Working Group.

How WebAssembly works?

In browsers, today Javascript is executed on a Virtual machine(VM) to optimize and outperform. Javascript is fast in execution but it can never be as fast ans=d as optimal as C or C++. That is the whole goal for WebAssembly. To be able to run code on any platform with efficiency.

Wasm runs in the same JavaScript VM, but performs much better. The two can communicate freely and don't exclude each other. This way you can have the best of both worlds - JavaScript's huge ecosystem and friendly syntax, combined with the near-native performance of WebAssembly.

Most people write WebAssembly modules in C and compile them to .wasm files. These wasm files aren't recognized by the browser directly, so they need something called JavaScript glue code to be loaded.

Picture from TuturialZine

Will WebAssembly replace JS?

WebAssembly is a different language from JavaScript, but it is not intended as a replacement. Instead, it is designed to complement and work alongside JavaScript,

WebAssembly is NOT going to kill JS! Not now. Maybe someday. - says browsers vendors.

Will we compile JS to WebAssembly?

JS is very dynamic that is not feasible to do so. Number conversions, bitwise and... Make JS a very bad language to target WASB.

WASB is a shortcut to your JS optimizer. -Ben Smith

WASB version 1 is very best suited for C++/C or Rust since there are still some features missing from WASB like garbage collections, threads. This makes WASB not ready to support higher level languages.

Other languages support should release soon. Like JAVA, OCaml, and even new ones like TurboScript.

When should you target WebAssembly?

Web Assembly is suitable for applications with heavily CPU bound computations, especially those dealing with numbers. Comparing to JS, you can use 64bit int in Web Assembly which you cannot have that in JS.
Most proper applications of WASB are:

  • Games using Unreal Engine in Chrome: Unity and Unreal Engine have plans to support WASM by end of 2017.

  • Deep Learning / Machine Learning

  • Virtual Reality

If you are interested exploring WebAssembly use this online WASB explorer to see compile your C++ code in action.