Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Javascript, should I delete previous level's instances after loading a new one?

I made an HTML5 game that consists of many small levels. When the player get's to the doors, another level is loaded. When a level is loading it basically just sets all the instance arrays to [] and then pushes stuff into them, by creating new instances of things, for example:

enemies = [] //this has previously been full of pointers from the old level
for (i = 0; i < n_enemies; i ++)
    enemies.push(new Enemy());

But, it has come to my attention that merely setting an array full of pointers to [], doesn't actually delete the instances! So, does javascript do this automatically? Or do I have to delete each instance myself?

like image 795
corazza Avatar asked Mar 05 '12 13:03

corazza


People also ask

How to delete an object created with new in JavaScript?

The only way to fully remove the properties of an object in JavaScript is by using delete operator. If the property which you're trying to delete doesn't exist, delete won't have any effect and can return true.

What is the purpose of the delete operator in JavaScript?

The JavaScript delete operator removes a property from an object; if no more references to the same property are held, it is eventually released automatically.

What is delete keyword in JavaScript?

The delete keyword deletes both the value of the property and the property itself. After deletion, the property cannot be used before it is added back again. The delete operator is designed to be used on object properties. It has no effect on variables or functions.


1 Answers

If the objects that were in the array are no longer referenced from anywhere then they will be garbage collected. There's no specification that states when this will occur, but it should be soon after removing them from the Array.

This should not present a memory leak.

like image 182
Jivings Avatar answered Sep 23 '22 05:09

Jivings