Understanding the fast alternative apply() in lodash

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?

Answers:

Answer

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.

Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.