Skip to content

Commit 31da975

Browse files
committed
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: #1221 Reviewed-By: Trevor Norris <[email protected]>
1 parent b64983d commit 31da975

File tree

1 file changed

+13
-23
lines changed

1 file changed

+13
-23
lines changed

lib/timers.js

+13-23
Original file line numberDiff line numberDiff line change
@@ -173,51 +173,41 @@ exports.active = function(item) {
173173
*/
174174

175175

176-
exports.setTimeout = function(callback, after, arg1, arg2, arg3) {
177-
var timer, i, args;
178-
var len = arguments.length;
179-
176+
exports.setTimeout = function(callback, after) {
180177
after *= 1; // coalesce to number or NaN
181178

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

186-
timer = new Timeout(after);
187-
188-
switch (len) {
183+
var timer = new Timeout(after);
184+
var length = arguments.length;
185+
var ontimeout = callback;
186+
switch (length) {
189187
// fast cases
190188
case 0:
191189
case 1:
192190
case 2:
193-
timer._onTimeout = callback;
194191
break;
195192
case 3:
196-
timer._onTimeout = function() {
197-
callback.call(timer, arg1);
198-
};
193+
ontimeout = callback.bind(timer, arguments[2]);
199194
break;
200195
case 4:
201-
timer._onTimeout = function() {
202-
callback.call(timer, arg1, arg2);
203-
};
196+
ontimeout = callback.bind(timer, arguments[2], arguments[3]);
204197
break;
205198
case 5:
206-
timer._onTimeout = function() {
207-
callback.call(timer, arg1, arg2, arg3);
208-
};
199+
ontimeout =
200+
callback.bind(timer, arguments[2], arguments[3], arguments[4]);
209201
break;
210202
// slow case
211203
default:
212-
args = new Array(len - 2);
213-
for (i = 2; i < len; i++)
204+
var args = new Array(length - 2);
205+
for (var i = 2; i < length; i++)
214206
args[i - 2] = arguments[i];
215-
216-
timer._onTimeout = function() {
217-
callback.apply(timer, args);
218-
};
207+
ontimeout = callback.apply.bind(callback, timer, args);
219208
break;
220209
}
210+
timer._onTimeout = ontimeout;
221211

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

0 commit comments

Comments
 (0)