Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Function calls are expensive" vs. "Keep functions small"

On the one hand, I read or hear that "function calls are expensive" and that they impact efficiency (for example, on Nicholas Zakas' Google tech talk).

On the other hand, however, it seems accepted that functions/methods are best kept short and should only really perform one task, as generally accepted in here.

Am I missing something here, or don't these two pieces of advice run contrary to one another? Is there some rule-of-thumb that allows one to maintain a Zen-like balance?

like image 208
Nick Avatar asked Jun 23 '12 10:06

Nick


People also ask

Are function calls expensive?

Speaking from personal experience, I write code in a proprietary language that is fairly modern in terms of capability, but function calls are ridiculously expensive, to the point where even typical for loops have to be optimized for speed: for(Integer index = 0, size = someList.

Are function calls expensive in JS?

Cost? About 2.78 microseconds per function call.

Does function call takes more time?

Long story short, the overhead of a direct (non-virtual) function call was approximately 5.5 nanoseconds, or 18 clock cycles, compared to an inline function call. The overhead of a virtual function call was 13.2 nanoseconds, or 42 clock cycles, compared to inline.


1 Answers

The general rule applying to all languages is: keep functions (methods, procedures) as small as possible. When you add proper naming, you get very maintainable and readable code where you can easily focus on general picture and drill down to interesting details. With one huge method you are always looking at the details and the big picture is hidden.

This rule applies specifically to clever languages and compiler that can do fancy optimizations like inlining or discovering which methods aren't really virtual so double dispatch isn't needed.

Back to JavaScript - this is heavily dependant on JavaScript engine. In some cases I would expect decent engine to inline function, avoiding the cost of execution, especially in tight loops. However, unless you have a performance problem, prefer smaller functions. Readability is much more important.

like image 168
Tomasz Nurkiewicz Avatar answered Sep 30 '22 03:09

Tomasz Nurkiewicz