最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

memory management - Javascript nested function performance - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question edited Aug 18, 2015 at 8:16 Dr1Ku 2,9103 gold badges48 silver badges57 bronze badges asked Nov 5, 2013 at 0:13 Khanh NguyenKhanh Nguyen 11.1k10 gold badges53 silver badges65 bronze badges 1
  • 2 This is not broad. It is very specific & practical... – Khanh Nguyen Commented Nov 5, 2013 at 0:18
Add a comment  | 

1 Answer 1

Reset to default 26

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.

发布评论

评论列表(0)

  1. 暂无评论