Skip to content

Commit

Permalink
lib: don't penalize setTimeout() common case
Browse files Browse the repository at this point in the history
The common case is where setTimeout() is called with two arguments,
the callback and the timeout.  Specifying optional arguments in the
parameter list forces common case calls to go through an arguments
adaptor stack frame.

PR-URL: #1221
Reviewed-By: Trevor Norris <[email protected]>
  • Loading branch information
bnoordhuis committed Mar 20, 2015
1 parent b64983d commit 31da975
Showing 1 changed file with 13 additions and 23 deletions.
36 changes: 13 additions & 23 deletions lib/timers.js
Original file line number Diff line number Diff line change
Expand Up @@ -173,51 +173,41 @@ exports.active = function(item) {
*/


exports.setTimeout = function(callback, after, arg1, arg2, arg3) {
var timer, i, args;
var len = arguments.length;

exports.setTimeout = function(callback, after) {
after *= 1; // coalesce to number or NaN

if (!(after >= 1 && after <= TIMEOUT_MAX)) {
after = 1; // schedule on next tick, follows browser behaviour
}

timer = new Timeout(after);

switch (len) {
var timer = new Timeout(after);
var length = arguments.length;
var ontimeout = callback;
switch (length) {
// fast cases
case 0:
case 1:
case 2:
timer._onTimeout = callback;
break;
case 3:
timer._onTimeout = function() {
callback.call(timer, arg1);
};
ontimeout = callback.bind(timer, arguments[2]);
break;
case 4:
timer._onTimeout = function() {
callback.call(timer, arg1, arg2);
};
ontimeout = callback.bind(timer, arguments[2], arguments[3]);
break;
case 5:
timer._onTimeout = function() {
callback.call(timer, arg1, arg2, arg3);
};
ontimeout =
callback.bind(timer, arguments[2], arguments[3], arguments[4]);
break;
// slow case
default:
args = new Array(len - 2);
for (i = 2; i < len; i++)
var args = new Array(length - 2);
for (var i = 2; i < length; i++)
args[i - 2] = arguments[i];

timer._onTimeout = function() {
callback.apply(timer, args);
};
ontimeout = callback.apply.bind(callback, timer, args);
break;
}
timer._onTimeout = ontimeout;

if (process.domain) timer.domain = process.domain;

Expand Down

0 comments on commit 31da975

Please sign in to comment.