Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What "use asm" does exactly?

As far as I know, Asm.js is just a strict specification of JavaScript, it uses the JavaScript features and it's not a new language.

For instance, instead of using var a = e;, it offers var a = e|0;.

My question is, if asm.js is just a definition and can be achieved by changing the way one uses and declares variables and dynamic types, what does "use asm"; actually do? Is this necessary to put this string before declaring function's body or not?

like image 655
Afshin Mehrabani Avatar asked May 03 '14 19:05

Afshin Mehrabani


2 Answers

Asm.js is a very strict subset of JavaScript, that is optimized for machines rather than humans. If you want your browser to interpret certain code as asm.js code, you need to create a module wherein the following conditions apply :

  • all code is fully statically typed and limited to the very restrictive asm.js subset of JavaScript
  • your module starts with the "use asm" pragma

Additionally, an asm.js module allows only up to three optional yet very specific parameters :

  • a standard library object, providing access to a subset of the JavaScript standard libraries
  • a foreign function interface (FFI), providing access to custom external JavaScript functions
  • a heap buffer, providing a single ArrayBuffer to act as the asm.js heap

So, your module should basically look like this :

function MyAsmModule(stdlib, foreign, heap) {
    "use asm";

    // module body...

    return {
        export1: f1,
        export2: f2,
        // ...
    };
}

The function parameters of your module allow asm.js to call into external JavaScript and to share its heap buffer with "normal" JavaScript. The exports object returned from the module allows external JavaScript to call into asm.js.

Leave out the "use asm", and your browser will not know that it should interpret your code as an asm.js module. It will treat your code as "ordinary" JavaScript. However, just using "use asm" is not enough for your code to be interpreted as asm.js. Fail to meet any of the other criteria mentioned hereabove, and your code will be also interpreted as "ordinary" JavaScript :

enter image description here

For more info on asm.js, see eg. John Resig's article from 2013 or the official specs.

like image 153
John Slegers Avatar answered Nov 11 '22 12:11

John Slegers


"use asm" is a pragma that tells the JavaScript engine specifically how to interpret it. Although it's valid JavaScript and can be used without the pragma, FireFox can perform additional optimizations to the Asm.js subset to increase performance. To do this, it must know that it is Asm.js.

like image 5
Syntax Avatar answered Nov 11 '22 13:11

Syntax