asm.js: Pushing the Limits of Browser Performance
It’s late 2012, and the "Web is too slow for games" argument is finally dying. Mozilla has just unveiled asm.js, a strict subset of JavaScript that can be used as a low-level, efficient target language for compilers. By restricting JS to only use integers, floats, and typed arrays, engines like OdinMonkey can perform Ahead-Of-Time (AOT) compilation and generate highly optimized machine code.
The Look of asm.js
Asm.js doesn't look like the JavaScript you write by hand. It uses "type hints" through bitwise operations to tell the engine exactly what types are being used.
function MyModule(stdlib, foreign, heap) {
"use asm";
var mem = new stdlib.Int32Array(heap);
function add(x, y) {
x = x | 0; // x is an int
y = y | 0; // y is an int
return (x + y) | 0;
}
return { add: add };
}
The "use asm"; directive tells the browser to validate the code. If it follows the strict rules, the browser bypasses the slow, heavy-weight JIT and uses a specialized compiler path.
Emscripten and the C++ Pipeline
Nobody actually writes asm.js. We use Emscripten to take existing C and C++ codebases and compile them. This is how we're seeing the Unreal Engine 3 running in a browser tab.
# Compiling a C++ file to asm.js
emcc hello.cpp -o hello.html --optimizations 3
Why Typed Arrays are Key
Asm.js relies entirely on a single ArrayBuffer as its "heap." All memory allocations from the C++ side are mapped into this buffer. Since there's no garbage collection for data inside the buffer, you get predictable performance-no more sudden frame drops during your game's boss fight because the GC decided to kick in.
While it's a bit of a hack, asm.js is proving that the browser is a viable platform for high-performance applications, paving the way for a more formal standard (some are already whispering about "WebAssembly").
Aunimeda develops websites and web applications for businesses - corporate sites, e-commerce, portals, and custom platforms.
Contact us to discuss your web project. See also: Web Development, E-commerce Development