Javascript Bitshift Performance

While working on 64-bit integer support in Javascript for Fan, I ran across a blurb about bit shift performance of Numbers. The basic gist was, since Javascript has to convert the number to an integer, perform the op, then convert back, multiplying or dividing by a power of two should be as fast, or faster. On the surface that might make sense, but I wanted to see for myself, so I hacked up a very naive test case:

var x = 0xffff;

var s = new Date().getTime();
for (var i=0; i<100000; i++) x = x >> 2;
var e = new Date().getTime();
var res1 = (e-s);
s = new Date().getTime();    
for (var i=0; i<100000; i++) x = x / 4;
e = new Date().getTime();
var res2 = (e-s); 
alert(">> " + res1 + "ms\n" + "/  " + res2 + "ms");

Very unscientific results:

Browser               >> 2    / 4
--------------------  ------  -------
Chrome     2-3ms   4-7ms
Firefox 3.0.11 (win)  11ms    15-16ms
Safari 3.1 (win)      15ms    15ms
IE8                   63ms    62-78ms
Opera 9.64 (win)      46ms    63ms

Interesting to see the different performance b/w browsers, but also seems clear, overall, the bit-shift operators perform slightly better even with the box/unbox hit.

Comments are closed.