zero
zero

Reputation: 3082

JavaScript patterns and garbage collection

I've been using two versions of a JavaScript pattern for a while that I picked up from Addy Osmani called the module pattern. view it here

The first version of this pattern uses an object literal:

var x = {
  b: function() {
    return 'text';
  },
  c: function() {
    var h = this.b();
    h += ' for reading';
  }
}
alert(x.b()) // alerts text.

while the other version uses a self executing function:

var y = (function() {
     var first = 'some value';
     var second = 'some other value';
     function concat() {
       return first += ' '+second;
     }

     return {
       setNewValue: function(userValue) {
         first = userValue;
       },
       showNewVal: function() {
         alert(concat());
       }
     }
})();

y.setNewValue('something else');
y.showNewVal();

Given the examples above, are either of these two patterns (not taking into account any event listeners) garbage collection friendly (given the way they reference themselves)?

Upvotes: 1

Views: 264

Answers (1)

Mike Samuel
Mike Samuel

Reputation: 120506

No. There's no difference as far as what becomes unreachable when.

Both use a global variable that pins the API in place, so will not be collectible until the frame is unloaded and dropped from history.

The second allocates and holds onto an extra activation frame (for module-locals first and second), but that's a pretty minor cost.

Upvotes: 1

Related Questions