Reputation: 155
I am new to memory management in JS, so please pardon if this is a dumb question.
Suppose I have a component with three functions defined and a switch case statement which calls only one function depending on the case matched. Will the other two functions occupy the memory or they are garbage collected once the switch statement is executed?
function funcA() {};
function funcB() {};
function funcC() {};
switch(type) {
case 'funcA':
funcA();
break;
case 'funcB':
funcB();
break;
case 'funcC':
funcC();
break;
}
Upvotes: 1
Views: 155
Reputation: 1202
If defined inside a function scope and not at the top-level of the document, any local variables referenced only inside that scope (including function definitions) will be garbage collected at some point after the function finishes executing.
You can verify this using FinalizationRegistry like so:
function memoryExperiment(type) {
function funcA() {};
function funcB() {};
function funcC() {};
const registry = new FinalizationRegistry((heldValue) => {
console.log(`Garbage collected ${heldValue}`)
});
registry.register(funcA, "funcA")
registry.register(funcB, "funcB")
registry.register(funcC, "funcC")
switch(type) {
case 'funcA':
funcA();
break;
case 'funcB':
funcB();
break;
case 'funcC':
funcC();
break;
}
return registry
}
const registry = memoryExperiment('funcA')
A message is logged for all three functions indicating they were garbage collected.
It is difficult to predict exactly when they will be collected as the garbage collection algorithm makes decisions based on various factors, but in my testing on an otherwise blank html file in Chrome it's usually after a few seconds.
Upvotes: 1