【问题标题】:Underscore.js Why using "switch' to handle cases instead of "for loop" [duplicate]Underscore.js 为什么使用“switch”而不是“for loop”来处理案例 [重复]
【发布时间】:2018-05-16 08:51:49
【问题描述】:

我正在尝试学习 underscorejs 源代码。以上是 underscore.js 源代码 VERSION = '1.9.0' 的代码 sn-p。正如你所看到的 switch 块和 for 循环:

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);
        };
};

为什么作者将switch中startIndex [0,1,2]的情况分开处理。

是不是因为在这些情况下必须运行循环,并且运行如此小的循环具有不必要的复杂性?如果这就是作者为什么只选择这3个案例为什么不选择[0,1,2,3]的原因。

他只选择这三个是有原因的还是只是一个选择。

【问题讨论】:

    标签: javascript performance optimization underscore.js


    【解决方案1】:

    我可以被认为是性能调整。

    IMO,[0,1,2] 可能涵盖实际项目中的大多数情况(大多数函数不会有太多参数)。

    而且,在典型的 JS 引擎中,callapply 快。看到这个JavaScript performance: Call vs Apply

    所以,结合以上两个方面,它可以使代码在大多数情况下运行得尽可能快,并保持源代码足够简单:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-10
      • 1970-01-01
      • 1970-01-01
      • 2019-04-23
      • 2015-01-11
      • 2014-01-11
      • 2012-10-28
      • 2011-05-19
      相关资源
      最近更新 更多