“Function calls are expensive” vs. “Keep functions small”

前端 未结 5 717
执笔经年
执笔经年 2020-12-12 23:45

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 oth

5条回答
  •  悲&欢浪女
    2020-12-13 00:36

    My rule of thumb is that it's time to break a function into smaller pieces if it is more than a screen-full of lines long, though many of my functions just naturally end up somewhat smaller than that without being "artificially" split. And I generally leave enough white-space that even a screen-full isn't really a whole lot of code.

    I try to have each function do only one task, but then one task might be "repaint the screen" which would involve a series of sub-tasks implemented in separate functions that in turn might have their own sub-tasks in separate functions.

    Having started with what feels natural (to me) for readability (and therefore ease of maintenance) I don't worry about function calls being expensive unless a particular piece of code performs badly when tested - then I'd look at bringing things back in-line (particularly in loops, starting with nested loops). Though having said that sometimes you just know that a particular piece of code isn't going to perform well and rewrite it before getting as far as testing...

    I'd avoid "premature optimisation", particularly with languages that use smart compilers that might do those same optimisations behind the scenes. When I first started C# I was told that breaking code up into smaller functions can be less expensive at run-time because of the way the JIT compiler works.

    Going back to my one screen-full rule, in JavaScript it is common to have nested functions (due to the way JS closures work), and this can make the containing function longer than I'd like if I were using another language, so sometimes the end result is a compromise.

提交回复
热议问题