Reputation: 319
I am currently trying to tackle some memory issue on our Javascript product and I would like to know if there was any chance that removing an item from an array via the splice
method could lead to any memory leak or is it equivalent to null the value to remove?
Does it change something if the array is stored in the global scope ?
For instance snippet 1:
var myArray = [...]; // init the array;
myArray.splice(indexOfTheItemToRemove, 1);
vs snippet 2 :
var myArray = [...]; // init the array;
var temp = myArray.splice(indexOfTheItemToRemove, 1);
temp.length = 0;
temp = null;
Thank you.
Upvotes: 4
Views: 3761
Reputation: 4266
According to Mozilla Developer Network:
Some function calls result in object allocation.
So, indeed, there is a memory allocation on splice
call.
However, Javascript has a garbage collector, which leads us to the next part of the article:
This is the most naive garbage collection algorithm. This algorithm reduces the definition of "an object is not needed anymore" to "an object has no other object referencing to it". An object is considered garbage collectable if there is zero reference pointing at this object.
Sure enough, as long as we're not assigning the result of the function to a variable, there are no references to it. Therefore, garbage collector could easily free the allocated memory.
We could easily check our assumption by running this piece of code in a browser:
var myArray;
var cycles = 100000;
var delay = 10;
(function step() {
myArray = ['a', 'b', 'c'];
myArray.splice(1, 1);
if (--cycles > 0) {
setTimeout(step, delay);
}
}());
We could inspect memory allocations on Chrome Dev Tools' Timeline tab.
The spikes point on a memory deallocation events, and we can see that the memory consumption level returns to its initial state.
So, the answer is: no, there is no memory leak here.
Upvotes: 11