嵌套助手功能和性能 [英] Nested helper functions and performance

查看:38
本文介绍了嵌套助手功能和性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嵌套的辅助函数可以使您的代码更易于理解.Google甚至建议在其样式指南中使用嵌套函数.我想知道这些嵌套函数和性能的实例化.例如,

Nested helper functions can be useful for making your code more understandable. Google even recommends using nested functions in their style guide. I'm wondering about the instantiation of these nested functions and performance. For example,

work(1);
work(2);

function work(a) {
    // do some stuff
    log();
    // do some more stuff
    function log() {
        console.log(a);
    }
}

work 实例化一次,但是 log 实例化两次?

work is instantiated once, but is log instantiated twice?

如果每次执行 work 时都会实例化 log ,通常是否建议不要嵌套函数?相反,请编写如下代码

If log is instantiated every time work is executed, would it generally be recommended not to nest functions? Instead, write code like the following

work(1);
work(2);

function work(a) {
    // do some stuff
    log(a);
    // do some more stuff
}

function log(a) {
    console.log(a);
}

这些示例过于琐碎,问题更多地是关于一般情况.

These examples are overly trivial and the question is more about the general case.

推荐答案

工作实例化了一次,但是日志实例化了两次?

work is instantiated once, but is log instantiated twice?

是的,每次致电 work .

通常建议不要嵌套函数吗?

would it generally be recommended not to nest functions?

为什么不呢?我想您是在暗示性能问题.

Why not? I presume you're hinting at performance issues.

一种习惯是好是坏取决于您使用它的原因.对于简单的助手,最好将它们保留在本地,因为这意味着您可以使它们适合于您的特殊情况,而不必担心常规功能的额外负担.例如.用前导零填充数字:

Whether a practice is good or bad depends on your reasons for using it. In the case of simple helpers, it's good to keep them local because it means you can make them suitable just for your special case and not worry about the extra cruft of a general function. E.g. to pad a number with a leading zero:

function pad(n) {
  return (n<10? '0' : '') + n; 
}

可以很好地用作辅助程序,其中 n 总是在0到99的范围内,但是由于通用函数缺少许多功能(以非数字n处理-ve个数字等).

works very well as a helper where n is expected to always be in the range 0 to 99, but as a general function is missing a lot of features (dealing with non–number n, -ve numbers, etc.).

如果您担心性能,则可以始终使用闭包,以便仅将一次实例化助手:

If you are concerned about performance, you can always use a closure so the helper is only instantiated once:

var work = (function() {

  function log() {
    console.log(a);
  }

  return function (a) {
    // do some stuff
    log();
    // do some more stuff
  };
}());

闭包中的多个函数在哪里使用 log 也是有意义的.

Which can also make sense where log is used by more than one function within the closure.

请注意,在单个情况下,这很大程度上是微优化,不太可能在性能上产生任何明显的差异.

Note that for a single case, this is very much a micro optimisation and not likely to deliver any noticeable difference in performance.

这篇关于嵌套助手功能和性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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