In Javascript, should you delete instances of a previous level after loading a new one?

I made an HTML5 game consisting of many small levels. When a player reaches the door, another level loads. When the level is loaded, it simply sets all the instance arrays to [] , and then inserts material into them, 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 occurred to me that just setting up an array with pointers to [] does not actually delete instances! So does javascript do this automatically? Or should I delete every instance of myself?

+6
source share
4 answers

If the objects in the array are no longer referenced anywhere, they will collect garbage. There is no specification that indicates when this will happen, but should soon be removed from the array.

This should not indicate a memory leak.

+3
source

I don’t know much about game development, but as a rule, in Javascript clear Array is done like that, and that’s good practice.

 enemies.length = 0; 

check this post

+2
source

It is like any other programming language. If there is a link to an object, it will not be deleted.

eg.

 enemies = []; enemy = new Enemy(); enemies.push(enemy); enemies = []; 

If you do not create a link to the object after emptying the enemies, the enemy object will also be deleted

 enemies.push(new Enemy()); 
+1
source

There is no free command in JavaScript, so you cannot free memory yourself. All you can do is: Kill all links (pointers) to any object. In the end, the garbage collector will look for objects that are no longer visible to anyone.

Or rather: the GC will eventually collect all the memory that can still be achieved and forget about everything else. That's why the cost of living objects is in the GC environment.

But there is one catch: GC does not inform objects that they are dead. Therefore, if your Enemy object needs some cleanup, you must do it manually.

+1
source

Source: https://habr.com/ru/post/909997/


All Articles