“功能调用很昂贵”。与“保持功能小”相对 [英] "Function calls are expensive" vs. "Keep functions small"

查看:112
本文介绍了“功能调用很昂贵”。与“保持功能小”相对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一方面,我读到或听到功能调用很昂贵并且影响效率(例如,关于Nicholas Zakas的Google技术讲座



然而,另一方面,似乎接受了最好保留的功能/方法简短,应该只执行一项任务,如此处所普遍接受的那样。 / p>

我在这里遗漏了什么,或者这两条建议是否相互冲突?是否有一些经验法则允许人们保持禅宗般的平衡?

解决方案

适用于所有语言的一般规则是:保持函数(方法,程序)尽可能小。当您添加适当的命名时,您将获得非常易于维护和可读的代码,您可以轻松地将注意力集中在一般图片上,并向下钻取以获得有趣的细节。使用一种巨大的方法,你总是在查看细节,并且隐藏了大图。



此规则专门适用于可以进行奇特优化的聪明语言和编译器,如内联或发现哪些方法不是真正的虚拟,因此不需要双重调度。



返回JavaScript - 这在很大程度上依赖于JavaScript引擎。在某些情况下,我会期望合适的引擎内联函数,避免执行成本,特别是在紧密循环中。但是,除非遇到性能问题,否则请选择较小的功能。可读性更重要。


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?

解决方案

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.

这篇关于“功能调用很昂贵”。与“保持功能小”相对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆