From 31da9758a0b9422faa5c2184c4a150118dfab615 Mon Sep 17 00:00:00 2001 From: Ben Noordhuis Date: Fri, 20 Mar 2015 16:55:19 +0100 Subject: [PATCH] lib: don't penalize setTimeout() common case 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: https://github.com/iojs/io.js/pull/1221 Reviewed-By: Trevor Norris --- lib/timers.js | 36 +++++++++++++----------------------- 1 file changed, 13 insertions(+), 23 deletions(-) diff --git a/lib/timers.js b/lib/timers.js index e5c0c9eaef746e..72f275a6421e62 100644 --- a/lib/timers.js +++ b/lib/timers.js @@ -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;