Oriol Oriol - 1 month ago 12
Javascript Question

Can regular JavaScript be converted to asm.js, or is it only to speed up statically-typed low-level languages?

I have read the question How to test and develop with asm.js?, and the accepted answer gives a link to http://kripken.github.com/mloc_emscripten_talk/#/.

The conclusion of that slide show is that "Statically-typed languages and especially C/C++ can be compiled effectively to JavaScript", so we can "expect the speed of compiled C/C++ to get to just 2X slower than native code, or better, later this year".

But what about non-statically-typed languages, such as regular JavaScript itself? Can it be compiled to asm.js?

Answer

Can JavaScript itself be compiled to asm.js?

Not really, because of its dynamic nature. It's the same problem as when trying to compile it to C or even to native code - you actually would need to ship a VM with it to take care of those non-static aspects. At least, such a VM is possible:

js.js is a JavaScript interpreter in JavaScript. Instead of trying to create an interpreter from scratch, SpiderMonkey is compiled into LLVM and then emscripten translates the output into JavaScript.

But if asmjs code runs faster than regular JS, then it makes sense to compile JS to asmjs, no?

No. asm.js is a quite restricted subset of JS that can be easily translated to bytecode. Yet you first would need to break down all the advanced features of JS to that subset for getting this advantage - a quite complicated task imo. But JavaScript engines are designed and optimized to translate all those advanced features directly into bytecode - so why bother about an intermediate step like asm.js? Js.js claims to be around 200 times slower than "native" JS.

And what about non-statically-typed languages in general?

The slideshow talks about that from …Just C/C++? onwards. Specifically:

Dynamic Languages

Entire C/C++ runtimes can be compiled and the original language interpreted with proper semantics, but this is not lightweight

Source-to-source compilers from such languages to JavaScript ignore semantic differences (for example, numeric types)

Actually, these languages depend on special VMs to be efficient

Source-to-source compilers for them lose out on the optimizations done in those VMs

Comments