Course contentsShow
← JavaScript
Lesson 522 of 2,72313. ClosuresFree lesson

Avoiding Closure Overhead

Recognize when closures add unnecessary memory costs and prefer shared prototypes or modules.

Avoiding Closure Overhead

You'll learn when closures cost more memory than they're worth, and how to choose lighter alternatives.

Closures are powerful, but they're not free. Every closure keeps a reference to its outer scope, which prevents garbage collection of those variables. When you create thousands of closures—especially in constructors or loops—you can inadvertently bloat memory.

The Hidden Cost

Each closure carries its lexical environment around like a backpack. If you create 10,000 objects using a factory function that returns closures for methods, you're creating 10,000 copies of those function objects, even if they all do the exact same thing.

// Heavy: Each user carries its own getName function
function createUser(name) {
  return {
    getName: function() { return name; }  // New function per user!
  };
}

const users = Array.from({length: 10000}, (_, i) => createUser(`User${i}`));
// 10,000 function objects in memory

Lighter Alternatives

Shared prototypes let all instances reference the same function:

function User(name) {
  this._name = name;
}
User.prototype.getName = function() {
  return this._name;
};

const users = Array.from({length: 10000}, (_, i) => new User(`User${i}`));
// Only ONE getName function in memory

The trade-off? You lose true private variables (the _name convention signals "private" but doesn't enforce it).

When to Use Each

  • Use closures for small-scale privacy needs, event handlers, memoization
  • Use prototypes when creating many similar instances
  • Use modules for singletons where one closure is fine

Key Takeaway: Closures retain their outer scope, which costs memory—prefer shared prototypes or module patterns when creating many similar objects that don't need unique closure state.