1

I am trying to learn underscorejs source code. The above is a code snippet from underscore.js source code VERSION = '1.9.0'. As you can see the switch block and for loop:

var restArguments = function(func, startIndex) {
        startIndex = startIndex == null ? func.length - 1 : +startIndex;
        return function() {
          var length = Math.max(arguments.length - startIndex, 0),
              rest = Array(length),
              index = 0;
          for (; index < length; index++) {
            rest[index] = arguments[index + startIndex];
          }
          switch (startIndex) {
            case 0: return func.call(this, rest);
            case 1: return func.call(this, arguments[0], rest);
            case 2: return func.call(this, arguments[0], arguments[1], rest);
          }
          var args = Array(startIndex + 1);
          for (index = 0; index < startIndex; index++) {
            args[index] = arguments[index];
          }
          args[startIndex] = rest;
          return func.apply(this, args);
        };
};

Why did the author handle cases of startIndex [0,1,2] in switch separately.

Is it because the loop will have to be run for these cases and its unnecessary complexity to run such small loops? If that's the reason why did the author select only these 3 cases why not [0,1,2,3].

Is there a reason he picked these 3 only or was it just a choice.

orangespark
  • 631
  • 6
  • 19

1 Answers1

2

I could be considered as performance tuned.

IMO, it might be possible that [0,1,2] could cover most cases in real projects(Most functions will NOT have too many arguments).

And, in typcial JS engines, call is faster than apply. See this JavaScript performance: Call vs Apply

So, combine above 2 aspects, it could make the code runs as faster as it can in most cases and keep the source code simple enough :)

yellowB
  • 2,900
  • 1
  • 16
  • 19