Clearing up memory in ThreeJS application

I'm facing challenges with memory management in my ThreeJS application.

I know there are already a few queries regarding this issue:

  • freeing memory in three.js
  • Freeing memory with threejs
  • Three.js Collada - What's the proper way to dispose() and release memory (garbage collection)?

I do release my objects using this Typescript function I've created :

function dispose( object3D: THREE.Object3D ): void
{
    // Dispose children first
    for ( let childIndex = 0; childIndex < object3D.children.length; ++childIndex )
    {
        this.dispose( object3D.children[childIndex] );
    }

    object3D.children = [];

    if ( object3D instanceof THREE.Mesh )
    {
        // Geometry
        object3D.geometry.dispose();

        // Material(s)
        if ( object3D.material instanceof THREE.MultiMaterial )
        {
            for ( let matIndex = 0; matIndex < object3D.material.materials.length; ++matIndex )
            {
                object3D.material.materials[matIndex].dispose();
                object3D.material.materials[matIndex] = null;
            }
            object3D.material.materials = [];
        }

        if ( object3D.material.dispose )
        {
            object3D.material.dispose();
            object3D.material = null;
        }
    }

    // Remove from parent
    if ( object3D.parent )
        object3D.parent.remove( object3D );

    object3D = null;
}

However, even after using heap snapshots in Chrome Dev Tools, I'm still seeing :

  • Arrays
  • Vector2 (uvs in __directGeometry, ...)
  • Vector3 (vertices in geometry, normal in faces, vertexColors in faces, ...)
  • Face3 (faces in geometry)
  • Color (colors in __directGeometry, ...)
  • JSArrayBufferData (color, normal, in attributes of geometry, ...)

Due to the large amount of data in memory, my app is being terminated by Jetsam on iOS, as mentioned here : Jetsam kills WebGL application on iOS

I suspect that some data within the library is not being properly released when requested.

Answer №1

Ensure everything is properly disposed of. This code snippet has been in use for quite some time. It handles the disposal of various materials, textures, and 3D objects by iterating through arrays and plain objects.

const dispose = function(object) {
    try {
        if (object && typeof object === 'object') {
            if (Array.isArray(object)) {
                object.forEach(dispose);
            } else if (object instanceof THREE.Object3D) {
                dispose(object.geometry);
                dispose(object.material);
                if (object.parent) {
                    object.parent.remove(object);
                }
                dispose(object.children);
            } else if (object instanceof THREE.Geometry) {
                object.dispose();
            } else if (object instanceof THREE.Material) {
                object.dispose();
                dispose(object.materials);
                dispose(object.map);
                dispose(object.lightMap);
                dispose(object.bumpMap);
                dispose(object.normalMap);
                dispose(object.specularMap);
                dispose(object.envMap);
            } else if (typeof object.dispose === 'function') {
                object.dispose();
            } else {
                Object.values(object).forEach(dispose);
            }
        }
    } catch (err) {
        console.log(err);
    }
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Firebase 9 - Creating a New Document Reference

Hey everyone, I need some help converting this code to modular firebase 9: fb8: const userRef = db.collection('Users').doc(); to fb9: const userRef = doc(db, 'Users'); But when I try to do that, I keep getting this error message: Fir ...

The process of passing parameter values by function in useEffect

Hi everyone, I hope you're all doing well. I'm currently facing an issue with trying to retrieve data from my API using the post method. The problem is that I can't use useEffect in any parameter. So, my workaround is to pass the data throug ...

What is the best approach to dynamically implement useReducer in code?

Take a look at the repository here: https://github.com/charles7771/ugly-code In the 'Options' component, I am facing an issue where I am hardcoding different names for each reducer case instead of dynamically generating them for a form. This app ...

Prevent the opening of tabs in selenium using Node.js

Currently, I am using the selenium webdriver for node.js and loading an extension. The loading of the extension goes smoothly; however, when I run my project, it directs to the desired page but immediately the extension opens a new tab with a message (Than ...

What is the reason for HereMap factoring in stopOver time when calculating travel time for the destination waypoint?

I am currently working on a request using the HereMap Calculate Route API. Waypoint 0 does not have any stopOver time, but waypoints 1 and 2 do have stopOver times. Below is an example of the request: https://route.ls.hereapi.com/routing/7.2/calculateroute ...

Retrieve a different action instance variable within the view

In the scenario where I have a View called home.html.erb and the corresponding controller shown below: class StaticController < ApplicationController def home @people = Person.all end def filter @people = .... end def contact end ...

Converting an array to an object using underscore: a beginner's guide

My array consists of different subjects: var subject = ["Tamil", "English", "Math"]; Now, I want to transform this array into an object, structured like this: [{ "name": "Tamil" }, { "name": "English" }, { "name": "Math" }] ...

The useEffect hook is not successfully fetching data from the local db.json file

I'm attempting to emulate a Plant API by utilizing a db.json file (with relative path: src\plant-api\db.json), and passing it from the parent component (ItemList) to its child (Item) but I am facing an issue where no data is being displayed ...

Executing multiple HTTPS requests within an Express route in a Node.js application

1 I need help with a route that looks like this: router.get('/test', async(req, res)=>{ }); In the past, I have been using the request module to make http calls. However, now I am trying to make multiple http calls and merge the responses ...

I'm attempting to render HTML emails in ReactJS

I have been attempting to display an HTML page in React JS, but I am not achieving the same appearance. Here is the code snippet I used in React JS: <div dangerouslySetInnerHTML={{ __html: data }}/> When executed in regular HTML, the page looks lik ...

Attempting to insert a line break tag within the text using React

Having trouble inserting line breaks in text using React. Can anyone guide me on how to achieve this? I've attempted adding the br tag, but it is displaying as in the browser. Here's a snippet of my code. Appreciate any help or advice. let sp ...

Using the OR Operator with a different function in React

Struggling with setting the day flexibility using disableDate(1,2,3,4,0) but it's not functioning as expected. Can you assist me in fixing this issue? Here is the function snippet: const disableDate = (date) => { const day = date.day(); retur ...

Best Method for Updating a Single Scope and Setting the Others to False in AngularJS

If I have 4 fields in my view that need to be toggled open or closed when clicked, with the requirement of closing the other three, how can this be achieved without duplicate code? <div class="square red"></div> <div class="square blue"> ...

Utilizing JavaScript, HTML, and CSS to incorporate images within circular frames

After finding inspiration from this question about rotating objects around a circle using CSS, I decided to modify the code to include images of Earth orbiting the Sun. The challenge was to make one image orbit another like a planet circling its star. Ear ...

Modifying the $scope within a controller

I need to update the $scope within the controller based on the object that is being clicked. The current code looks like this: var blogApp = angular.module('blogApp', ['ngSanitize', 'ngRoute']); blogApp.controller('blog ...

Exploring the Depths of the DOM: Enhancing User Experience with Jquery

I am facing an issue with my AJAX request in my page. After retrieving data from the database and trying to append it to a div, I am attempting to create an accordion interface without success. Below is a snippet of my source code after the AJAX call: ...

Angular JavaScript Object Notation structure

I am a beginner in AngularJS and I'm attempting to create formatted JSON based on the values of table rows (tr) and cells (td). The table rows are generated automatically. When the form is submitted, I try to create the JSON values. Once the form is ...

Utilizing the invoke() method within the each() function in Cypress to access the href attribute

I recently started using Cypress and I'm attempting to retrieve the href attribute for each div tag within a group by utilizing invoke(), however, it is resulting in an error. Could anyone provide guidance on the correct way to achieve this? cy.get(&a ...

Encountering a TypeError in semantic-ui-react Menu: instance.render function not found

As a React novice, I have been working on a project that involves React for some time. However, I had not yet delved into dealing with packages and dependencies. It seems like my current issue is related to this. The problem emerged in a project where I w ...

Retrieve JSON and HTML in an AJAX request

I have multiple pages that heavily rely on JavaScript, particularly for sorting and filtering datasets. These pages typically display a list of intricate items, usually rendered as <li> elements with HTML content. Users can delete, edit, or add item ...