24

I'm curious about these jsperf results. They appear to demonstrate that a direct function call is substantially faster than the same function called with .call or .apply. (The difference between .call and .apply surprised me even more.) Could you please explain these results?

Update: Here is a jsperf that someone left that tests .apply without a second array instantiation.

5
  • 6
    Well, for one thing, there's at least one more function call involved (the call to ".call()" or ".apply()") ... Commented Nov 18, 2011 at 15:06
  • 2
    ... and, indeed, it's about half as fast to go through ".call()" or ".apply()", which is about what you'd expect it'd cost to do two function calls instead of just one. Commented Nov 18, 2011 at 15:08
  • 8
    .apply is slower because you're constructing an array as well. Commented Nov 18, 2011 at 15:11
  • 2
    @Pointy that is a decent empirical explanation, except that according to Yehuda Katz, function.call() and obj.func() should be desugared to the same internal invocation of [[Call]]. So it should only be one call either way. Commented Nov 18, 2011 at 16:08
  • In iPad, the performances of apply and call are the same. Commented Feb 25, 2012 at 20:55

1 Answer 1

7

I guess the cause might depend on which interpreter your are running the code on, but it seems that normal functions calls are faster because the interpreter can use Inline Cache to access the properties.

You can have a look here for more information.

Sign up to request clarification or add additional context in comments.

5 Comments

If you run this [test][1] you'll notice that .call is as fast as normal call, maybe because the interpreter as difficulties with the type inference when an array contains different type of values...
What do you mean by 'the interpreter can use Inline Cache to access the properties': what properties?
I meant the object properties. When you call obj.myProp in javascript, the interpreter need to loop through all properties in the object to check which one corresponds to "myProp". One of the possible optimization is to "remember" the index of this property in the object property list and directly jump to this property on the next function call.
yes, it seems to be broken now. I vaguely remember it pointed to a presentation of David Mandelin. From the link name, you can probably find the same material here: conferences.oreilly.com/velocity/velocity2011/public/schedule/… (the pdf f this link is relevant for the answer anyway).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.