Skip to content

Instantly share code, notes, and snippets.

@bhaveshdaswani93
Created November 24, 2019 08:19
Show Gist options
  • Save bhaveshdaswani93/a342b32152f35c664ec6ea731dc831ca to your computer and use it in GitHub Desktop.
Save bhaveshdaswani93/a342b32152f35c664ec6ea731dc831ca to your computer and use it in GitHub Desktop.
In this example we will see how closure are memory efficient
function withOutClosure(index) {
const arr = new Array(8000).fill('Lorem ipsum olorem'); // some random heavy operation that generate data
return arr[index];
}
withOutClosure(543);
withOutClosure(6543);
withOutClosure(345);
withOutClosure(135);
//In above each when function is called our data set is created and then when function execution finishes the function is removed from the
// the stack as well as the data is removed as it is not referenced anywhere else so the garbage collector will remove the variable
// It is not memory efficent because every time the function is called the heavy operation is executed to generate the data set which is
// not efficient. Here Closue comes to rescue
function withClosure() {
const arr = new Array(8000).fill('Lorem ipsum olorem'); // some random heavy operation that generate data
return function(index) {
return arr[index];
}
}
const findFromIndex = withClosure();
findFromIndex(20);
findFromIndex(290);
findFromIndex(4567)
// Here the variable array is created once and on each execution of findFromIndex we are refrencing arr variable from closure.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment