Javascript嵌套函数性能 [英] Javascript nested function performance

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

问题描述

我有一些嵌套函数,例如

I have some nested functions such as

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

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

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

因此,如果 freak 被调用很多次,这意味着将浪费大量内存(假设 die 没有使用 freak 的上下文;换句话说,即使它只分配一次并在多次调用 freak 之间共享,它也能正常工作——这就是我所说的 wasted).

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?

推荐答案

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

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.

所以如果 freak 被调用很多时间,那意味着大量内存将被浪费 [...]

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

对于一些非常小且通常无关紧要的浪费"值.

JavaScript 引擎如今非常高效,可以执行各种技巧/优化.

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?

没有.没有 浪费"问题 如果没有实际 测试用例,则不然.这个习惯用法(嵌套函数和匿名函数)在 JavaScript 中很常见,并且针对它进行了很好的优化.

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天全站免登陆