DEV Community

Discussion on: Use Closures for Memory Optimizations in JavaScript (a case study)

Collapse
 
miketalbot profile image
Mike Talbot ⭐

My point is that a local primitive variable in a function is allocated on the stack and not in the main heap of memory (it's different if it is an object), this memory isn't "being used" it's just an offset from the current stack pointer.

The moment we "close over" a function then the function definition is converted internally into a class and the value of that variable becomes a property of the instance of that class. The stack is a super efficient way of handling primitive value storage during the execution of a function. If x was an object then it wouldn't be the same story, as the reference to x would be stored on the stack but the contents of x would be allocated in memory and be subject to subsequent garbage collection, leading to additional processing requirements. In neither of these cases would the variable be "used" as in it wouldn't continue to take up required memory after the function exited, however as Javascript uses garbage collection it would need processing for the memory to be made available again.


function multiply(y) {
    let x = 10 ** 10
    return y * x
}

// This function does NOT allocate 10000000 copies
// of x in memory, the same location on the stack is used each time.
//  No additional memory will be consumed and
// there will be no garbage collection
for(let i = 0; i < 10000000; i++) {
    console.log(multiply(i))
}


Enter fullscreen mode Exit fullscreen mode

Consider this:


function multiply(y) {
    let x = {pow: 10 ** 10}
    return y * x.pow
}

// This function DOES allocate 10000000 copies of x in memory,
// however NO additional memory will be permanently held
// as garbage collection will free the temporary values as they are no longer
// accessible.
for(let i = 0; i < 10000000; i++) {
    console.log(multiply(i))
}


Enter fullscreen mode Exit fullscreen mode