ThreeJS Disposing an Object

The disposal of unwanted library entities is a crucial component of improving performance and avoiding memory leaks in your programme. When you create a three.js type instance, you set aside a specified amount of memory. Three.js, on the other hand, builds WebGL related things like buffers and shader programmes for specific objects like geometries and materials, which are required for rendering. It's vital to note that these objects aren't automatically released. In order to liberate such resources, the programme must instead use a particular API. This document gives a quick overview of how to use this API and what objects are useful in this situation.

Geometries

A geometry is typically used to represent vertex information in the form of a set of characteristics. For each attribute, three.js produces an object of type WebGLBuffer internally. These entities are only deleted if you call BufferGeometry.dispose(). Execute the procedure to liberate all relevant resources whenever a geometry becomes obsolete in your application.

Materials

A material is what determines how an object is presented. three.js constructs a shader programme for rendering using information from a material specification. Shader programmes can only be removed if the corresponding material is no longer in use. Three.js aims to reuse existing shader programmes whenever possible for speed reasons. As a result, a shader programme is only removed when all associated materials have been discarded. You can indicate the disposal of a material by executing Material. Dispose().

Textures

The texture of a material is unaffected by its disposal. Because a single texture might be utilised by many materials at the same time, they are treated independently. Three.js automatically creates a WebGLTexture instance whenever you create a Texture instance. This object, like buffers, can only be removed by invoking Texture.dispose ().

Miscellaneous

Other instances directory classes, like as controls and post processing passes, include dispose() methods for removing internal event listeners and render targets. In general, it's a good idea to examine a class's API or documentation for disposal (). If it's present, you should make use of it when cleaning up.

Let’s good at some commonly asked questions

Why can't three.js dispose objects automatically?

The community has raised this subject several times, so it's critical to address it. The truth is that three.js has no idea how long user-created things like geometries or materials will last or what their scope will be. This is the application's duty. Even though a material isn't being utilised for rendering right now, it can be required in the following frame. So, if the application thinks that a particular object can be erased, it must inform the engine by invoking the dispose() method.

Does removing a mesh from the scene also dispose its geometry and material?

No, you must dispose of the geometry and material specifically using dispose (). Keep in mind that 3D objects like meshes can share geometry and materials.

What happens when you call dispose() on a texture but the image is not loaded yet?

Internal texture resources are only allocated after the image has completely loaded. Nothing happens if you dispose of a texture before the image has been loaded. There were no resources assigned, so there is no need to clean up.

Does three.js provide information about the amount of cached objects?

Yes. WebGLRenderer.info, a specific property of the renderer that contains a series of statistics information on the graphics board memory and the rendering process, can be evaluated. It tells you how many textures, geometry, and shader programmes are saved inside, among other things. It's a good idea to debug this property if you discover performance issues in your application so you can quickly find a memory leak.

How should I manage three.js objects in my app? When do I know how to dispose things?

There is no clear suggestion for this in general. When invoking discard() is appropriate, it is greatly dependent on the unique use case. It is critical to emphasise that disposing of artefacts is not always essential. A game with numerous levels is an excellent example of this. When transferring levels, this is an excellent time to dispose of objects.

The app could go over the original scene and remove any materials, geometries, or textures that were no longer needed. It does not create a runtime error if you dispose an object that is still in use, as indicated in the previous section. The worst that can happen is a single frame of performance degradation.


Related Topics

ThreeJS AnimationObjectGroup and Utils

AnimationObjectGroup A group of objects that receives a shared animation state. Usage Add items you'd normally send as 'root' to AnimationMixer's function Object() { [native code] } or clipAction method, and instead pass...

2 minutes read.

ThreeJS Raycaster

This class is intended to help with raycasting. Raycasting is used for a variety of purposes, including mouse picking (determining which objects in 3D space the mouse is over). Code Example const...

4 minutes read.

ThreeJS AnimationAction

AnimationActions are used to schedule the playback of animations saved in AnimationClips. Note that the majority of AnimationAction's methods can be chained together. The "Animation System" page in the "Next Steps" part...

6 minutes read.

ThreeJS Helpers 2

PolarGridHelper The PolarGridHelper is an object to define polar grids. Grids are two-dimensional arrays of lines. Code Example const radius = 10; const radials = 16; const circles = 8; const divisions = 64; const helper =...

4 minutes read.

ThreeJS Materials 3

RawShaderMaterial This class works just like ShaderMaterial, except that definitions of built-in uniforms and attributes are not automatically prepended to the GLSL shader code. Code Example const material = new THREE.RawShaderMaterial( {    ...

9 minutes read.

ThreeJS Compatibiliy Check and Running Locally

Even though this is becoming less of an issue, some devices or browsers may still be incompatible with WebGL. The method below enables you to check if it is supported...

3 minutes read.

ThreeJS Audio

It is used to create a non-positional (global ) audio object. Code Example: // create an AudioListener and add it to the camera const listener = new THREE.AudioListener(); camera.add( listener ); // create a global...

6 minutes read.

ThreeJS Renderers

WebGLMultipleRenderTargets A special render target that enables a fragment shader to write to several textures. This approach is useful for advanced rendering techniques like post-processing or deferred rendering. Heads up: WebGLMultipleRenderTargets...

15 minutes read.

ThreeJS Helper 1

ArrowHelper A 3D arrow object for visualizing directions. Code Example const dir = new THREE.Vector3( 1, 2, 0 ); //normalize the direction vector (convert to vector of length 1) dir.normalize(); const origin = new THREE.Vector3( 0,...

5 minutes read.

ThreeJs Tutorial

What is Three.JS? Three.js is a cross-browser JavaScript library and application programming interface that uses WebGL to create and display animated 3D computer graphics in a web browser. The source code...

6 minutes read.

ThreeJS Using post-processing

Many three.js applications render their 3D objects directly to the screen. Sometimes, however, you want to apply one or more graphical effects like Depth-Of-Field, Bloom, Film Grain or various types...

2 minutes read.

ThreeJS Loaders 2

ImageBitmapLoader A loader that converts an image to an ImageBitmap. An ImageBitmap provides an asynchronous and resource-efficient path for preparing textures for WebGL rendering. ImageBitmapLoader, unlike FileLoader, does not prevent multiple concurrent...

8 minutes read.

ThreeJS Disposing an Object

The disposal of unwanted library entities is a crucial component of improving performance and avoiding memory leaks in your programme. When you create a three.js type instance, you set aside...

4 minutes read.

ThreeJS BufferGeometry

A mesh, line, or point geometry representation. Included within buffers are vertex positions, face indices, normals, colours, UVs, and custom attributes, lowering the cost of passing all of this data...

5 minutes read.

ThreeJS Math

Box2 Represents an axis-aligned bounding box (AABB) in 2D space. Constructor Box2( min : Vector2, max : Vector2 ) min - (optional) Vector2 representing the lower (x, y) boundary of the box. Default is...

48 minutes read.

ThreeJS Lights

Light Abstract base class for lights - all other light types inherit the properties and methods described here. Constructor Light( color : Integer, intensity : Float ) color - (optional) hexadecimal color of the...

10 minutes read.

ThreeJS Testing with npm

This article explains how to install three.js in a node.js environment so that automated tests may be run. Tests can be done manually or with the help of automated CI...

4 minutes read.

ThreeJS BufferAttribute

This class stores data for an attribute associated with a BufferGeometry (such as vertex positions, face indices, normals, colours, UVs, and any custom attributes), allowing for more efficient data passing...

4 minutes read.

ThreeJS Keyframe Tracks and Animation

A KeyframeTrack is a timed series of keyframes that are made up of lists of times and related values and are used to animate an object's unique property. BooleanKeyframeTrack A Track of...

3 minutes read.

ThreeJS Object3D

This is the base class for most three.js objects, and it provides a set of properties and methods for manipulating objects in 3D space. It should be noted that this can...

9 minutes read.