const heavyData = { /* large data structure */ };
function createClosure() {
const data = heavyData;
return function() {
console.log("Closure created");
// Never actually uses data
};
}
const closures = [];
for (let i = 0; i < 1000; i++) {
closures.push(createClosure());
}
This code demonstrates excessive memory usage from unnecessary closure variables: 1) Each closure captures a reference to the heavyData object in its lexical environment, 2) Despite never actually using the data, each closure keeps it in memory, 3) With 1000 closures, the same large data structure is effectively referenced 1000 times, 4) This pattern multiplies memory consumption without any benefit, 5) The issue is that closures capture their entire enclosing environment, not just the variables they use, 6) A better approach would be to avoid including the heavy data in the closure's scope if it's not needed, 7) This demonstrates how closures can inadvertently cause memory inefficiency, 8) Understanding closure behavior is crucial for memory-efficient JavaScript.