Dispose Objects in Threejs

Dispose of objects

One important aspect in order to improve performance and avoid memory leaks in your application is the disposal of unused library entities. Whenever you create an instance of a three.js type, you allocate a certain amount of memory. However, three.js creates for specific objects like geometries or materials WebGL related entities like buffers or shader programs which are necessary for rendering. It’s important to highlight that these objects are not released automatically. Instead, the application has to use a special API in order to free such resources. This guide provides a brief overview about how this API is used and what objects are relevant in this context.

Geometries

A geometry usually represents vertex information defined as a collection of attributes. three.js internally creates an object of type WebGLBuffer for each attribute. These entities are only deleted if you call BufferGeometry.dispose(). If a geometry becomes obsolete in your application, execute the method to free all related resources.

Materials

A material defines how objects are rendered. three.js uses the information of a material definition in order to construct a shader program for rendering. Shader programs can only be deleted if the respective material is disposed. For performance reasons, three.js tries to reuse existing shader programs if possible. So a shader program is only deleted if all related materials are disposed. You can indicate the disposal of a material by executing Material.dispose().

Textures

The disposal of a material has no effect on textures. They are handled separately since a single texture can be used by multiple materials at the same time. Whenever you create an instance of Texture, three.js internally creates an instance of WebGLTexture. Similar to buffers, this object can only be deleted by calling Texture.dispose().

If you use an ImageBitmap as the texture’s data source, you have to call ImageBitmap.close() at the application level to dispose of all CPU-side resources. An automated call of ImageBitmap.close() in Texture.dispose() is not possible, since the image bitmap becomes unusable, and the engine has no way of knowing if the image bitmap is used elsewhere.

Render Targets

Objects of type WebGLRenderTarget not only allocate an instance of WebGLTexture but also WebGLFramebuffers and WebGLRenderbuffers for realizing custom rendering destinations. These objects are only deallocated by executing WebGLRenderTarget.dispose().

Leave a comment

Your email address will not be published. Required fields are marked *