lib: don't penalize setTimeout() common case
authorBen Noordhuis <info@bnoordhuis.nl>
Fri, 20 Mar 2015 15:55:19 +0000 (16:55 +0100)
committerBen Noordhuis <info@bnoordhuis.nl>
Fri, 20 Mar 2015 22:42:26 +0000 (23:42 +0100)
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 <trev.norris@gmail.com>
lib/timers.js

index e5c0c9eaef746ed1056ac16ebb41261bd87086ad..72f275a6421e62bae75522bfff5e1a7cc31b1bd5 100644 (file)
@@ -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;