Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are .call and .apply slower than a direct function call in JavaScript?

Tags:

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.

like image 414
kojiro Avatar asked Nov 18 '11 15:11

kojiro


People also ask

How slow are function calls Javascript?

About 2.78 microseconds per function call.

Are function calls expensive in Javascript?

Function calls in Javascript are less expensive than the maintenance nightmare caused by poorly-organized code.

Is foreach inefficient?

Foreach performance is approximately 6 times slower than FOR / FOREACH performance. The FOR loop without length caching works 3 times slower on lists, comparing to arrays. The FOR loop with length caching works 2 times slower on lists, comparing to arrays.


1 Answers

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.

like image 155
F-A Avatar answered Sep 21 '22 13:09

F-A