Archive for June, 2009

Javascript Bitshift Performance

Tuesday, June 16th, 2009

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

Fan AST Viewer

Friday, June 12th, 2009

After spending way too much time trying to debug my Fan to Javascript compiler, I broke down and hacked up a little FWT-based AST viewer. I’m pretty sure we’ll fold this into the core distro, just need to clean up the code first, and figure out where to put it.

Fan AST Viewer

Extending built-in types

Tuesday, June 2nd, 2009

I ran into an issue where I really needed to tag the built-in Javascript types with additional information to make Fan work better.  The big one is annotating a Number to be either a Int or Float, which you need to do to make all the equality checks work consistently (since 5 != 5f).

This is was my first attempt, which I assumed would work:

>>> var x = 15;
>>> x.$fanType = sys_Type.find("sys::Int");
>>> x.$fanType
undefined

But no dice.  After a bit of googling, I found this page, which says in order to add properties to the built-in types, you must create objects using the constructor syntax:

>>> var x = new Number(15);
>>> x.$fanType = sys_Type.find("sys::Int");
>>> x.$fanType
"sys::Int"

I assume this a performance optimization, where you can use a primitive int value in the first case, and have to allocate an object in the latter. Though since Javascript is a pure-OO language, I would be interested in seeing how VMs actually implement this behavoir.

Edit 8 Jun 09: Just realized using the object syntax breaks equality checks for numbers:

>>> var x = new Number(4);
>>> var y = new Number(4);
>>> x == y
false

Which sort of sucks, but you can work around it using valueOf, but still annoying.

>>> x.valueOf() == y.valueOf()
true