I have a javascript array of objects that are each created with 'new'. In the event of an error I would like to clear the whole array so that it would be GC'ed by the JS engine. To this end is it sufficient to just set the array variable to 'null' or do I need to splice all the elements from the array and set them to null before setting the array variable to 'null'?
The reason I am asking is that in Firefox I displayed (console.log) the array before assigning it to null and the displayed object (which is usually updated in the display I assume even later) still shows the elements of the array when I inspect it later, hence my doubt if the elements are actually being free'd or not.
Array elements can be deleted using the JavaScript operator delete . Using delete leaves undefined holes in the array. Use pop() or shift() instead.
Some high-level languages, such as JavaScript, utilize a form of automatic memory management known as garbage collection (GC). The purpose of a garbage collector is to monitor memory allocation and determine when a block of allocated memory is no longer needed and reclaim it.
Garbage collection is performed automatically. We cannot force or prevent it. Objects are retained in memory while they are reachable.
Hence there is no explicit way to allocate or free up memory in JavaScript. Just initializing objects allocates memory for them. When the variable goes out of scope, it is automatically garbage collected(frees up memory taken by that object.)
To clear an array you can just set the length to zero:
var arr = [1,2,3,4,5];
console.log(arr);
arr.length=0;
console.log(arr);
Result:
[1, 2, 3, 4, 5]
[]
Edit: Just found this on the topic: http://davidwalsh.name/empty-array
Looking at the comments it seems that just setting the variable to a new array is the simplest method:
arr = [];
According to the test results the memory is GC'd quicker than setting the length to 0. I would imagine this is to do with the allocations triggering the GC.
There is an interesting performance test on various methods here: http://jsperf.com/array-destroy
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With