tick, tock… Time waits for No One

Ok so what I am about to discuss might be old news for most but for me it’s new. After discovering this I have to admit that I am a bit disappointed in myself for not already knowing this.

When implementing asynchronous methods in Node I had always done the following:

function asynchProcessFunc = function(callback) {
    setTimeout(function(callback){
        // process the request now
        callback(returnData);
    }, 0);

    // return back 
};

It was recommended by someone that I change this out for the process.nextTick(cb) method. Being a firmware developer in previous lifetimes the pure mention of tick had me intrigued.

Was it actually processing CPU ticks?

Turns out the answer was No but still what I did find was something far better than a zero based timeout. I had always known that setTimeout(cb, timer) with a zero based timer was never going to be accurate but I had decided it was the best I could ever get.

To get an idea of a difference between the two I wrote the following to measure setTimeout:

setTimeout(function(){
    var startTime = process.hrtime();

    setTimeout(function() {
        var timeDiff = process.hrtime(startTime);
        console.log('setTimeout time diff - ', timeDiff[0]*1e9 + timeDiff[1], '(nanoSecs)');
    }, 0);
}, 1000);

I rounded the average rate to 1600000.

I then changed the program to use process.nextTick() like the following:

setTimeout(function(){
    var startTime = process.hrtime();

    process.nextTick(function() {
        var timeDiff = process.hrtime(startTime);
        console.log('nextTick time diff - ', timeDiff[0]*1e9 + timeDiff[1], '(nanoSecs)');
    });	
}, 1000);

I rounded the average rate to 400000, which gives me a difference of about 4x performance increase. Depending on your product this I am sure will change but even the improvement comes in at 2x that is still a major performance increase.

Happy coding everyone.