javascriptgoogle-chromeoptimizationv8

chrome javascript optimization deep magic


I'm optimizing an sha-256 > hmac > pbkdf2 crypto algorithm in javascript for chrome

http://jsfiddle.net/dtudury/uy3hc/

if I change one line (after the comment // BREADCRUMB ) ei = (di + t1) >>> 0; to ei = (di + t1); my test still passes, but the test runtime jumps from <1s to 7s

I believe the >>> 0 tells chrome that it should store the value as an (actual) int... but there's some degree of "cargo cult" to it.

My question is: "is this documented anywhere?" I'd love to verify how this works and/or find a zero operation way to tell chrome about ints (and any other secret ways of anticipating the chrome js compiler that such a document would reveal)

thank you!


Solution

  • The general principle is that yes, Chrome / V8 tries to figure out if your code is consistently dealing with a particular type (like ints), and optimizing for that case. There are a bunch of posts and presentations about Javascript JIT strategies on the web... e.g. here and here.

    In this specific case, though, my guess is that it's a bug. For one, I can't reproduce it in node.js. Moreover, replacing (di + t1)>>>0 with other common int-casting 'type hints' like (di + t1)|0 and ~~(di+t1) don't seem to improve things in Chrome. Finally, running Chrome with --js-flags="--trace-opt --trace-deopt --code-comments" shows that in the slow case, _hashWords is getting deoptimized and re-optimized dozens of times, which probably makes it even slower than if no optimizations were attempted at all. (I guess this is the CPU equivalent of thrashing.) Interestingly, the reason provided for deoptimization is shift-i, which sounds like the compiler keeps assuming that the numbers aren't integers, and then getting surprised each time it encounters an integer-shifting instruction.

    To answer your specific question, the exact way that Chrome compiles things isn't documented, but the general principles and the methods of profiling and debugging performance issues are. Here's my favorite series of posts on profiling -- it's written by the guy who works on the Dart-to-JS compiler.

    Edit: Doh, I just realized that >>> 0 is casting to an unsigned int, while |0 and ~~ cast to a signed int. That's probably why Chrome's V8 couldn't resolve the type properly.