Should I Bother Cleaning Array In Node.js?
Solution 1:
Can I just do:
i = i + 1; array[i] = null;
Or would it lead to large consumption of memory?
Yes, considering that array
is a global variable and won't get garbage-collected itself, filling it constantly with values (even if only null
ones) will eventually let you run out of memory.
Your get_id
approach that recycles unused ids does work, but is horribly inperformant - it requires linear time to find a new id. So it'll work for few users with few concurrent missions, but it won't scale.
You'll rather want to use an object and delete
keys from it, then you don't get into problems when just counting up:
var count = 0;
var missions = {};
functionsomethingThatNeedsTheStore() {
var id = count++;
missions[id] = …;
// laterdelete missions[id];
}
// repeatedly call somethingThatNeedsTheStore()
Or actually, on recent node versions, you should consider using a Map
instead:
var count = 0;
var missions = new Map;
function somethingThatNeedsTheStore() {
var id = count++;
missions.set(id, …);
// later
missions.delete(id);
}
// repeatedly call somethingThatNeedsTheStore()
Solution 2:
NodeJS has a garbage collector to destroy unreachable object/array/variable.
So when you do array[i] = {large object};
, the large object will be in the memory and it will stay here. When you do array[i] = null;
, the garbage collector will erase the large object (only if there's no other reference to this object of course).
So yes, it is always good to remove references to useless objects to let the garbage collector clean it.
The impact on the memory of an array of 1000 null
(or undefined) will not be very big.
If you want to preserve your memory, you should use an object instead of an array. You can use it with this syntax :
var obj = {};
obj[id] = {large object};
// Free the id
delete obj[id];
Post a Comment for "Should I Bother Cleaning Array In Node.js?"