Hacker News new | past | comments | ask | show | jobs | submit login

Anyone have more insight into the statement "Avoid closures"? Or rather, an alternative to having private functions?



They mentioned memory leaks as their reasoning. Run the following program in any browser and you will see the memory usage balloon out of control:

    var theThing = null;

    function replaceThing(){
      var oldThing = theThing;
      function unused(){ return oldThing }
      theThing = {
        longStr: new Array(1000000).join('*'),
        someMethod: function(){ }
      };
    }

    setInterval(replaceThing, 1000);
V8 (and all other engines I tested) will save the oldThing variable in someMethod's lexical environment record, causing each Thing to keep a reference to the previous Thing, preventing it from being garbage collected. This is despite the fact that the old thing is actually unreachable - someMethod never uses the oldThing variable.

For a more detailed explanation, check out the post that I lifted this example from: http://point.davidglasser.net/2013/06/27/surprising-javascri...


Example of Google's Closure Compiler eliminating the memory leak:

    var theThing = null; 

    function replaceThing() {
      theThing = {
        longStr: Array(1E6).join("*"),
        someMethod: function() { }
      }; 
    } 

    setInterval(replaceThing, 1E3);
http://closure-compiler.appspot.com/home


I interpret 'Avoid closures' as just don't define a function within your function. Private functions are simply functions that haven't been exported and aren't really closures (if we're talking about using a module pattern, at least).

Excessive closures can lead to memory leaks. Anonymous closures are a PITA when debugging.


Closures are fine, but avoid seagulls:

function() {

  function() {

     function() {

        function() {

        }

      }

   } 

}


"Seagulls" amazing! I'm used to calling them pyramids of doom, or laser guns.


Looks a bit less like seagulls if you do "});" instead of plain "}" though


We call it arrow code. The arrow points down a path of deep despair and frustration.


I think this is going to catch on.


Seagulls?


First I've heard the word used in this context, but I assume it refers to the appearance of the braces forming a 'V' pattern of what look like seagulls.


Deeply nested closures are harder to inline and optimize. If you want fast code then the easiest way to accomplish that is with explicitly spelling out everything in the prototype instead of generating closures.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: