What “use asm” does exactly?

喜夏-厌秋 提交于 2019-12-04 10:32:31

问题


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?


回答1:


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 :

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




回答2:


"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.



来源:https://stackoverflow.com/questions/23448804/what-use-asm-does-exactly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!