Understanding the fast alternative apply() in lodash

寵の児 提交于 2019-11-26 18:39:00

问题


I read the source code of lo-dash, and find there is fast alternative the function apply() here.

  function apply(func, thisArg, args) {
    switch (args.length) {
      case 0: return func.call(thisArg);
      case 1: return func.call(thisArg, args[0]);
      case 2: return func.call(thisArg, args[0], args[1]);
      case 3: return func.call(thisArg, args[0], args[1], args[2]);
    }
    return func.apply(thisArg, args);
  }

I want to know is that really efficient way to implement the fast alternative function apply()? Why there is no more than 3 args to decomposed here?


回答1:


You would need to bench test speed differences to be sure.

See this SO post on speed differences between call and apply:

Why is call so much faster than apply?

So it's not really a "faster" apply, it just executes call if it can.

It will take more than 3 arguments, the last line is a catch all that calls the standard apply.

Presumably _lodash has considered that having a huge long switch determining how many arguments are passed in defeats the purpose and decided to limit it to three.




回答2:


The simple answer: it's optimizing for the common case. The fastest path here is to call a function without any arguments (it's the first case in the switch). As it turns out, that's the most common way to call a function. The next most common calls are with 1, 2, and 3 arguments.

Functions called with 4+ arguments are rare enough that there's no justification to add more code here.



来源:https://stackoverflow.com/questions/33730955/understanding-the-fast-alternative-apply-in-lodash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!