Should I help the GC to free unused variables ?
The problem is that something eats memory on my program ,either an object or an array. I see the memory getting bigger and bigger only on a certain Load Stress on the Backend (Kubernetes on the Cloud , not locally).
The question is , should I set any array that I don't need to undefined
once I'm done using it in any place on my code ?
For example:
async emitMessageToKafka(......) {
let someArray: any[] = [];
// manipulations of "someArray"
// Emit to Kafka "someArray"
someArray = undefined; // Correct of not ??
// ...
// ...
}
CodePudding user response:
Should I help the GC to free unused variables?
It should be left to the GC to decide whether to free memory to which there is no more (strong) reference.
should I set any array that I don't need to undefined once I'm done using it in any place on my code?
No, not in general.
If there isn't much more time or memory-consuming activity happening in the execution context that has the scope of that variable, then it is useless. For instance, here it would be useless:
async func() {
let someArray = [];
// ... working with someArray ...
await someAsyncFunc(someArray);
someArray = undefined;
return 1 2 * 3;
}
The reference to that array is anyway lost when the function executes that return
, so there is no gain. Either way, the GC can free the related memory.
However, it could help when the rest of the execution is significant, and will still have that variable in scope, but your code will not use that variable anymore.
For instance:
async func() {
let someArray = [];
// ... working with someArray ...
await someAsyncFunc(someArray);
someArray = undefined;
await someAsyncFunc2();
// ... some more code that doesn't use someArray ...
// ...
}
That could be useful, as it allows the GC to already free the memory for the array (if there are no other references to it) while someAsyncFunc2
has not yet resolved. But in that case, it is better practice to limit the scope of your variable, like so:
async func() {
{
let someArray = [];
// ... working with someArray ...
await someAsyncFunc(someArray);
}
await someAsyncFunc2();
// ... some more code that CANNOT use someArray ...
// ...
}