Javascript Optimizing for Speed

I’m in the process of developing a CPU intensive Javascript game. I found the profilers of the different browsers lacking and needed some higher resolution probing of CPU hogger sections in the code. To this effect I created the timers manager below. Basically at any point in the code where you want to start measuring something, say data sorting, you add the line g_timers.begin("my data sort"); and at the end of where the code does its thing you add the line g_timers.pause("my data sort");. You can add as many checkpoints as you see fit for different part of the code – just make sure the string timer identifier passed to the g_timers.begin method is identical to the one passed to the corresponding g_timers.pause method.

Finally, whenever you want to see a report of the accumulated times of all the timers you’ve planted, simply call g_timers.show(). You might probably also want to call g_timers.reset() after that to zero all the accumulated time measurements.

var timers = {};
timers.new = function()
{
    var self = {}
    var t1,total;

    self.begin = function(id) {
        t1[id] = +new Date();
        if (!(id in total))
            total[id] = 0;
    }

    self.pause = function(id) {
        if (id in t1) {
            var t2 = +new Date();
            total[id] += t2-t1[id];
            t1[id] = t2;
        }
    }

    self.show = function() {
        console.log( "Total times:")
        for (id in total)
            console.log( id+": "+total[id]+" ms." );
    }

    self.reset = function() {
        t1    = {};
        total = {};
    }

    self.reset();
    return self;
}

var g_timers = timers.new();

I think IE6 does not like the above method of creating the JavaScript object – if you have problems, just use your own flavor.

Leave a Reply

Your email address will not be published. Required fields are marked *