Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How expensive are function calls in JavaScript?

I've been looking at other people's JavaScript code, and I've noticed that many programmers tend to create functions that could be combined with the functions that are calling them. One example is this; the 'initWebGL' function could be combined with the 'start' function and it'd function the same. Another example is in the source of this, where function 'tick', which is called every 15 milliseconds, makes calls to two other functions that may just as well be combined with 'tick'. I understand the organizational qualities of this, but I am curious about the effect on performance. Is doing this good practice, especially considering that JavaScript is an interpreted language?

like image 727
Skofo Avatar asked Jan 17 '10 08:01

Skofo


People also ask

Is function call expensive?

They don't cost very much at all — at least not in most compiled languages. It is nonetheless interesting to examine the costs involved. It is even more interesting to find out that a function call could be the dominant cost in your program.

Do function calls slow down code?

On one hand, functions are great as a concept that makes software more readable a easier to maintain. On the other hand, too much calls to tiny functions doing little work can definitely slow things down.

How slow are function calls JavaScript?

About 2.78 microseconds per function call.

How long do function calls take?

Function calls (depending on the platform) typically involve a few 10s of instructions, and that's including saving / restoring the stack. Some function calls consist a jump and return instruction.


1 Answers

Best practice for any language is to write code that is readable and maintainable first, and then to optimize if needed.

If your program runs fast enough split into easy-to-digest chunks, then leave it that way. If it's running slowly, then like hobodave mentioned, profile to find the cause of the slowness.

Chances are, it's going to be caused by something other than calling functions, but if it happens to be caused by that, then start combining functions together, once you've tracked it down to that.

like image 146
pib Avatar answered Nov 03 '22 05:11

pib