stickfigure stickfigure - 5 months ago 7
Node.js Question

Is console.time() safe in node.js?

I have a little snippet of node.js code in front of me that looks like this:

console.time("queryTime");
doAsyncIOBoundThing(function(err, results) {
console.timeEnd("queryTime");
// Process the results...
});


And of course when I run this on my (otherwise idle) development system, I get a nice console message like this:

queryTime: 564ms


However, if I put this into production, won't there likely be several async calls in progress simultaneously, and each of them will overwrite the previous timer? Or does node have some sort of magical execution context that gives each "thread of execution" a separate console timer namespace?

Answer

Just use unique labels and it will be save. That's why you use a label, to uniquely identify the start time.

The reason for this is quite simple: console.time and console.timeEnd are one of the simplest functions of the world (source):

Console.prototype.time = function(label) {
  this._times.set(label, Date.now());
};


Console.prototype.timeEnd = function(label) {
  var time = this._times.get(label);
  if (!time) {
    throw new Error('No such label: ' + label);
  }
  var duration = Date.now() - time;
  this.log('%s: %dms', label, duration);
};

As long as you don't accidentally use a label twice everything will work exactly as intended. Also note that node has usually only one thread of execution.

Comments