Unable to remove unnecessary shapes in a three.js project

In this simple example, I am adding a THREE.SphereGeometry to a THREE.Group and then including the group in the scene. After rendering the scene, my goal is to eliminate the group from the scene and dispose of the geometry.

<html>
<head>
  <title>memory-leak-demo-01</title>
  <script type='module'>

    import * as THREE from '../lib/three-js-129/build/three.module.js';

    let canvas = document.createElement('canvas');
    let renderer = new THREE.WebGLRenderer({ canvas:canvas, antialias: true });
    let camera = new THREE.PerspectiveCamera();
    let scene = new THREE.Scene();
    scene.add(camera);

    function getGroup(){
      let group = new THREE.Group();
      const geometry = new THREE.SphereGeometry( 5, 8, 8 );
      const material = new THREE.MeshBasicMaterial( {color: 0xffff00, wireframe: true} );
      group.add(new THREE.Mesh( geometry, material ));
      return group;
    }

    for(let i=0; i<1000; i++){
      let myGroup = getGroup();
      scene.add(myGroup);
      renderer.render(scene, camera);
      scene.remove(myGroup);
      console.log(`${i} renderer.info.memory: ${JSON.stringify(renderer.info.memory)}`);          
    }

  </script>
</head>
</html>

The issue lies in the fact that even after removing myGroup from the scene, the geometries are not cleared from memory as shown by console logging.

992 renderer.info.memory: {"geometries":993,"textures":0} 
993 renderer.info.memory: {"geometries":994,"textures":0} 
994 renderer.info.memory: {"geometries":995,"textures":0} 
995 renderer.info.memory: {"geometries":996,"textures":0} 
996 renderer.info.memory: {"geometries":997,"textures":0}
997 renderer.info.memory: {"geometries":998,"textures":0} 
998 renderer.info.memory: {"geometries":999,"textures":0} 
999 renderer.info.memory: {"geometries":1000,"textures":0}

I am seeking guidance on how to properly use .dispose() to remove these geometries. My aim is to only dispose of geometries within the group while keeping other objects in the scene intact.

In the actual application I am developing, there are numerous geometries within the group and the group is added and removed from the scene with each requestAnimationFrame cycle. This results in constant memory consumption leading to system slowdowns.

A demo page featuring the above code can be accessed here:

Another page showcasing the same issue but with visible spheres being rendered:

Answer №1

It's important to have your cleanup code structured like this:

for(let i=0; i<1000; i++){
      let group = getGroup();
      scene.add(group);
      renderer.render(scene, camera);
      scene.remove(group);
      const model = group.children[ 0 ];
      model.geometry.dispose(); // UPDATE
      model.material.dispose(); // UPDATE
      console.log(`${i} renderer.info.memory: ${JSON.stringify(renderer.info.memory)}`);          
    }

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

Unexpected behavior encountered when using onClick in a material-ui List component containing Buttons

Looking to implement a customized list using React and Material-UI, where each item features a Checkbox, a text label, and a button. The onClick event for the Checkbox should be managed by a separate function from the onClick event for the Button. Encount ...

Retrieving Values from Array Objects - Using JavaScript

Discovering the technique to retrieve property values. Given the following: let object1 = [{name: "HappyHands31"}, {job: "website developer"}, {city: "Chicago"}]; How can I output only the value of the second object, which is "website developer"? I am ...

Ensuring that Bootstrap rows fill the entire height within a column

While working on a template with nested rows and columns in Bootstrap, the layout ended up looking like this: <div class="col-5"> <div class="row"> <div class="col-3 border border-secondary">Truck Number</div> ...

Utilizing Ajax to retrieve an array of input textboxes and showcase the outcome within a div container

This is the form that I have designed for displaying information: <form name='foodlist' action='checkout' method='POST'> <table> <tr> <td>Product Name</td> <td>Price</t ...

How to transfer data from local storage to PHP using Ajax

Is there a way to pass values from JavaScript to PHP that are stored in local storage? JavaScript let cartItems = localStorage.getItem("productsInCart"); var jsonString = JSON.stringify(cartItems); $.ajax({ url:"read.php", method: "post", da ...

Is there a method to prevent the json file from being constantly overwritten?

After running this code, I noticed that even when inputting a different userId, it still ends up overwriting the existing user instead of adding a new one as intended. const user = userId; const userObj = {[user]:valueX}; words.users = userObj; f ...

Embedded Javascript fails to function following an async postback triggered by an UpdatePanel

After embedding some JavaScript files in a server control, everything works fine. However, when the server control is placed within an ajax UpdatePanel, it ceases to function after an async postback triggered within the updatepanel. This is the code in th ...

Connect Zebra Browser Print with Vue 2.0

I am currently working on integrating the Zebra BrowserPrint-1.0.4.js into Vue. You can find the code snippet at the following link: https://gist.github.com/robinsk/a667a490b7ef8192bbb9fcfc87f15757 However, I am facing an issue when trying to save the obj ...

Unable to use .click function to choose image within container

Apologies for the lengthy post, but I believe providing all details is essential to understanding the issue at hand. The following code snippet is intended to display the first image in a pop-up box when a user clicks on any of the images shown: <div ...

Seeking a jQuery tooltip plugin that offers support for inline popups similar to overLib

Let's dive into the code: <form name='form 1' action='$action'> input tags <table> some tr tags along with td tags and after some lines in the same table under a td tag <td> <a href="javascript:void(0);" oncli ...

Tips for enabling autofocus in mat-select列表。

I am working on an angular project where I am using Angular Material and a mat-select element. In my form, the mat-select is the first element, and I want to set auto-focus on it when the page loads. However, I have been facing some difficulties achieving ...

What is the correct way to run javascript on a DOM element when ng-show is triggered?

For those who prefer shorter explanations, there's a TLDR at the end. Otherwise, here's a detailed breakdown. I have a form that consists of multiple inputs organized into different "pages" using ng-show. What I aim to achieve is when ng-show r ...

Error encountered: "Unable to process Three.js FontLoader due to SyntaxError

I attempted to generate 3D text with FontLoader in Three.js, but encountered an error. My Three.js version is r99. const loader = new THREE.FontLoader(); //https://github.com/mrdoob/three.js/tree/dev/examples/fonts loader.load("./fonts/helvetiker_ ...

The process of styling with styled components in Mui - a guide to styling

Currently, I am facing challenges with styling and organization while working on a new react project with material ui and styled components. Despite researching best practices for styled components, I am still struggling to find an effective solution for s ...

Is there an equivalent function to onAdd in Material-UI when using MUI Chip?

In my exploration of the latest version of Material-UI, MUI, I observed that the "onAdd" property has been removed. The only function properties remaining are "onDelete" and "onClick". I am interested in generating new chips based on user-input tags. Is ...

What could be causing a react element to fail to update?

I'm currently working on a React component that interacts with a MaterialUi text form. The component utilizes a useState hook to update based on the input received. My goal is to have another variable update when the form is submitted, which will be d ...

Initiating Ajax to trigger the body's onLoad event

Whenever I use an ajax call to load a div, the entire page refreshes. It seems that the 'body onload=init()' event is triggered on ajax response causing all the initialization to repeat, which is not desired. Is there a way to only load the div t ...

Ways to retrieve an array following a function call

After a lot of testing and troubleshooting, I finally got my array to function properly in the console. However, when I click the button, the array is displayed on the console but not in my HTML. TS: jogar(){ for(var u=0;u<6;u++){ this.y ...

Angular 2 property accessor designed similar to Linq style

Many times, we come across an array (IEnumerable) property where we need to extract specific values. In C#, we can achieve this by using the following code snippet: public AssetModel PromoImage { get { return Assets.FirstOrDefa ...

Error compiling template due to custom component issue

Can you help me troubleshoot my custom component? I'm trying to create a setup with: label input Why am I seeing the error message "idfor is undefined"? And what's causing the issue with labeltext? An unexpected identifier was found in the ...