Javascript嵌套功能性能 [英] Javascript nested function performance

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

问题描述

我有一些嵌套函数,比如

  var freak = function(){
var die = function ){...}
die(this);
}

据我所知,死于函数将在每次调用 freak 时被创建(分配)。所以如果 freak 被调用了很多时间,这意味着很多内存将被浪费(假设 code> die 没有使用 freak 的上下文中的任何内容;换句话说,即使它只被分配了一次并在 freak 多次调用之间共享 - 这就是我的意思是浪费了 )。

我的理解是否正确?这是否意味着应该完全避免嵌套函数?

解决方案


据我所知,每次调用 freak 时, die 函数都会被创建(分配)。


是的。这是真的。创建一个新的函数对象。


因此,如果 freak 被调用了很多的时间,这意味着大量的内存将被浪费[...]

对于一些非常小而且通常无关紧要的

JavaScript引擎现在非常高效,可以执行各种各样的技巧/优化。



例如,只有函数对象(但不是 的实际功能代码!)需要在内部复制。


[...]是否意味着应该完全避免嵌套函数?

没有。如果没有 实例测试用例,则显示 浪费问题。这个习惯用法(嵌套函数和匿名函数)在JavaScript中非常普遍,并且非常适合。



嵌套函数提供了很多好处,包括自我 - 文档化代码,较小的自包含词法范围以及其他代码隔离/组织优势。

I have some nested functions such as

var freak = function() {
    var die = function() { ... }
    die(this);
}

As far as I have learned, the die function will get created (allocated) each time freak is called.

So if freak gets called a lot of time, that means a lot of memory will be wasted (assuming die is not using anything from freak's context; in other words, it works fine even if it was allocated only once and shared between multiple calls of freak – this is what I meant with wasted).

Is my understanding correct? And does that mean nested functions should be avoided entirely?

解决方案

As far as I have learned, the die function will get created (allocated) each time freak is called.

Yes. This is true. A new function-object is created.

So if freak gets called a lot of time, that means a lot of memory will be wasted [...]

For some very small and normally inconsequential value of "wasted".

JavaScript engines are very efficient these days and can perform a wide variety of tricks/optimizations.

For instance, only the function-object (but not the actual function code!) needs to be "duplicated" internally.

[...] does that mean nested functions should be avoided entirely?

No. There is no "wasting" problem without an actual test-case that shows otherwise. This idiom (of nested and anonymous functions) is very common in JavaScript and very well-optimized for.

Nested functions provide many benefits including self-documenting code, smaller self-contained lexical scopes, and other code isolation/organization advantages.

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

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