Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript array deletion for garbage collection

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.

like image 897
source.rar Avatar asked Jul 23 '13 09:07

source.rar


People also ask

How do you delete array completely in JavaScript?

Array elements can be deleted using the JavaScript operator delete . Using delete leaves undefined holes in the array. Use pop() or shift() instead.

How is garbage collection handled in JavaScript?

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.

Can users prevent garbage collection in JavaScript?

Garbage collection is performed automatically. We cannot force or prevent it. Objects are retained in memory while they are reachable.

How do I free up memory in JavaScript?

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.)


1 Answers

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

like image 190
RobH Avatar answered Sep 20 '22 01:09

RobH