Javascript nested function performance

后端 未结 1 1296
南笙
南笙 2020-12-10 12:42

I have some nested functions such as

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

As far as I have learned, t

相关标签:
1条回答
  • 2020-12-10 13:11

    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 讨论(0)
提交回复
热议问题