Alan
Alan

Reputation: 574

Dynamically create and destroy a Three.js scene without leaking memory

Lets say we had a page with two buttons, create and destroy. When you click create the Three.js scene in this memory test below is dynamically added to the page and starts running. Clicking destroy should remove the scene, dealocate all buffers and free up all memory etc. http://mrdoob.github.com/three.js/examples/webgl_test_memory.html

Does anyone know how to do this without framing the scene and changing the url?

thanks

Upvotes: 5

Views: 6143

Answers (3)

user3006521
user3006521

Reputation: 31

I think you need to using the dispose() method in side geometry, material and texture.

geometry.dispose();
material.dispose();
texture.dispose();

https://github.com/mrdoob/three.js/blob/master/examples/webgl_test_memory.html

Upvotes: 2

Gaurav
Gaurav

Reputation: 1088

I myself was troubled with this question for long, raised bug reports with chrome and Three.js but was not able to find any solution.

For some reasons memory does not free up even after a long time and seems something keeps pointing to memory block and hence garbage collector never free it up.

However here is what did the trick for me

  1. Create an array which will hold all items added to scene.
  2. Whenever you add an extra item to scene, add it to this array.
  3. On destroy function, run scene.remove('item name') to remove them from scene.
  4. Now iterate through array and manually make all the items undefined.

Following this way, I was able to claim more than 600MB of RAM from Three.js scene.

update

Answer by Mr. Doob and WestLangley Memory leak with three.js and many shapes, I am yet to test this with my code.

In webGLRenderer, after removing a mesh with

scene.remove( mesh ),

you can deallocate the memory with

renderer.deallocateObject( mesh );

You can deallocate textures with

renderer.deallocateTexture( texture );

Upvotes: 1

Claudiu
Claudiu

Reputation: 229321

JavaScript is a garbage-collected language. If you no longer have any references to a certain object (like an old scene), then the memory will eventually be reclaimed, unless there is a bug in the implementation somewhere. The page you linked to seems to work fine, though.

Upvotes: 1

Related Questions