Question

If I have a large array I'm using all the time and continuously through-out the lifetime of the app, such as a user list. And yes I enjoy using arrays rather than objects for many reasons and can't use splice() because I have index references.

The usual quote for garbage collection:

Since Javascript is garbage collected, you don't need to delete objects themselves - they will be removed when there is no way to refer to them anymore.

Does this mean that when I delete an element in an array, since the array can be referred to at any time - the Garbage collector wont free up the deleted element? or does it mean because the object can't be referred to, it will free up memory? - And even if it is, wont my array get filled up with 'undefined' entries which presumably use up at least 1 or 2 bytes of memory? - does anyone know how much memory is used per undefined entry?

Example:

var userList = [];
var userNumber = 0;

userList[userNumber++] = {name:'john',score:200,friends:['abby','micky']};
userList[userNumber++] = {name:'jack',score:200,friends:['betty','billy']};
userList[userNumber++] = {name:'jimm',score:200,friends:['catty','ken']};

delete userList[1];
// will {name:'jack',score:200,friends[ n ]} size of memory be freed 
// or a little less to internally reference 'undefined'?
Was it helpful?

Solution

When you delete an array property, its value becomes unreachable*, hence freeable by the garbage collector as soon as you delete them.

a = [0, 1, 2]
alert(1 in a);  // true
delete a[1];
alert(1 in a);  // false

* - assuming the array element is not otherwise reachable from a property of a reachable object or live local variable.


... - the Garbage collector wont free up the deleted element? or does it mean because the object can't be referred to, it will free up memory?

The garbage collector is never obliged to free any memory, but can reuse any memory previously used by the value of a deleted array property that is not otherwise referenced by any property or live local variable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top