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