Search code examples
javascriptassemblybrowserv8

What are the best practices for optimising JavaScript for (potential) future browser assembly-language optimisations?


As I understand it, the V8 engine in Chrome has been using assembly level optimisations for some time, and now the (at the time of writing) upcoming release of OdinMonkey on Firefox indicates that extensive low-level optimisations are being written into browsers for JavaScript.

I hope this is within SO's etiquette, but my question is three fold...

  1. (a specific question that I suppose may be edited out) — With regards to Firefox's OdinMonkey/asm.js optimisation — is this something "We" have to code for specifically? Or is it similar to the V8 engine in that it all happens 'behind the scenes'? The sources I have seen either on this specific topic seem to be contradictory.

  2. More generally (and perhaps a more pertinent question) are there any best practices with regards to coding JavaScript for better 'ahead-of-time'/assembly/etc. optimisation? For example, I have read that using bitwise shifts to round numbers MAY improve optimisation, but, depending on the browser it may cause little to no gain.

  3. Rolling this into a third question to prevent confusion — Finally, are client-side assembly level optimisations fruitless? Should 'We' as coders just try the best we can to produce efficient JavaScript code, and let the optimisation procedures do their best?


Solution

  • You have to target asm.js specifically by using only low-level constructs and strict typing. A single violation of numerous asm.js restrictions will abort entire compilation and fall back to regular JS VM.

    You can't take advantage of asm.js by merely tweaking existing JS code. It's not guaranteed that asm.js-style JS will be any faster in regular JS VM. It may be better suited for optimizations, but OTOH asm.js requires lots of casting that other VMs may not optimize out as well.

    For V8 and rest of Firefox's VM Zoo rules are the same — don't mix types, don't use eval or with anywhere, etc.