Learn WebAssembly
上QQ阅读APP看书,第一时间看更新

Mozilla and asm.js

Mozilla debuted asm.js in 2013 and provided a way for developers to translate their C and C++ source code to JavaScript. The official specification for asm.js defines it as a strict subset of JavaScript that can be used as a low-level, efficient target language for compilers. It's still valid JavaScript, but the language features are limited to those that are amenable to ahead-of-time (AOT) optimization. AOT is a technique that the browser's JavaScript engine uses to execute code more efficiently by compiling it down to native machine code. asm.js achieves these performance gains by having 100% type consistency and manual memory management.

Using a tool such as Emscripten, C/C++ code can be transpiled down to asm.js and easily distributed using the same means as normal JavaScript. Accessing the functions in an asm.js module requires linking, which involves calling its function to obtain an object with the module's exports.

asm.js is incredibly flexible, however, certain interactions with the module can cause a loss of performance. For example, if an asm.js module is given access to a custom JavaScript function that fails dynamic or static validation, the code can't take advantage of AOT and falls back to the interpreter:

The asm.js AOT compilation workflow

asm.js isn't just a stepping stone. It forms the basis for WebAssembly's Minimum Viable Product (MVP). The official WebAssembly site explicitly mentions asm.js in the section entitled WebAssembly High-Level Goals.

So why create WebAssembly when you could use asm.js? Aside from the potential performance loss, an asm.js module is a text file that must be transferred over the network before any compilation can take place. A WebAssembly module is in a binary format, which makes it much more efficient to transfer due to its smaller size. 

WebAssembly modules use a promise-based approach to instantiation, which takes advantage of modern JavaScript and eliminates the need for any is this loaded yet? code.