The performance of Three.js noticeably declines when objects are constantly removed and added

Recently, I started experimenting with three.js by building a basic shooting game. In this game, the user is required to shoot colored crates (boxes). When a crate is shot, it disappears and another random crate appears in its place.

if (intersects.length > 0) {
             intersects[0].object.material.color.setHex(Math.random() * 0xffffff);
                  scene.remove(object);
                  create_cube();
                  animate();
...

Initially, the game runs smoothly without any lag. However, as more boxes are shot, the game starts to experience performance issues.

I'm concerned whether I may be mishandling memory allocation or garbage collection. Any advice would be appreciated.

You can view my code on JSfiddle here: https://jsfiddle.net/k0s2nmru/

(Interestingly, while the standalone version of my code works fine, it encounters issues when integrated into JSfiddle)

Update:

To monitor the performance, I have integrated stats provided by three.js which report good frames per second (up to 150 and higher), despite the visible lag in the game. Could there be a better way to implement the stats feature?

Answer №1

Upon initial inspection, I can identify 3 methods to enhance the efficiency of your code

1) Avoid unnecessary calls to animate or render

    function onDocumentMouseDown(event) {
        var mouse3D = new THREE.Vector3();
        var raycaster = new THREE.Raycaster();
        mouse3D.normalize();
        controls.getDirection(mouse3D);
        raycaster.set(controls.getObject().position, mouse3D);
        var intersects = raycaster.intersectObjects(objects);
        if (intersects.length > 0) {
     intersects[0].object.material.color.setHex(Math.random() * 0xffffff);
          scene.remove(object);
          create_cube();
          animate();     //  AVOID THIS

        }
        renderer.render(scene, camera);   //  AVOID THIS
      }

The render operation is carried out within a tight loop, managed by requestAnimationFrame. It is not necessary to call them outside of this loop as it disrupts the requestAnimationFrame optimizations due to potential concurrent loops.

2) Strive for optimal rendering at all times.

     controls.getObject().translateX(velocity.x * delta);
     controls.getObject().translateY(velocity.y * delta);
     controls.getObject().translateZ(velocity.z * delta);

     if (controls.getObject().position.y < 10) {

Consider creating a temporary variable to store the result of controls.getObject() for improved optimization.

3) Repurpose when possible

In alignment with yomotsu's suggestion, consider disabling the visibility of the impacted cube upon collision, adjusting its color and position, and then reinstating its visibility.

Answer №2

When you delete an object, it's important to also remove the associated geometry, material, and texture in order to free up resources that are cached in the renderer.

scene.remove( mesh );
// Perform cleanup
geometry.dispose();
material.dispose();
texture.dispose();

For a practical example, you can check out this demo:

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

Having trouble targeting multiple dropdowns using jQuery

I am encountering an issue with two separate dropdowns where the hover states cannot be targeted by CSS based on the HTML markup. After attempting to solve this using jQuery, I have made some progress but one problem persists. Whenever I hover over the lin ...

When switching windows or tabs, the user interface of the browser extension vanishes

As someone who is new to web application development and browser extension creation, I have encountered a challenge with my browser extension. When the extension popup is open and I switch browser windows, the UI (popup.html) disappears. It reappears whe ...

JavaScript pause until image finishes uploading

The code snippet below contains 3 alert() functions that should be fired in order: first alert(1), then alert(2), and finally alert(3). However, due to the img.onload() function, alert(3) is being triggered before alert(2). var _URL = window.URL || window ...

Challenges with retrieving all text records in a profile using ethers.js

Currently, I am facing difficulties in retrieving all ENS text records from a profile due to issues with the logic or potential approaches... With ethers.js v6, my current strategy involves fetching all the log data and then sifting through it. However, t ...

The specified selector is invalid or illegal in HTMLUnit

Attempting to mimic a login using htmlunit has presented me with an issue despite following examples. The console messages I have gathered are as follows: runtimeError: message=[An invalid or illegal selector was specified (selector: '*,:x' erro ...

Remove a textbox dynamically in jQuery using solely jQuery without the use of traditional JavaScript code

My code is aimed at creating a dynamic way to add and remove textboxes. However, I am encountering a problem where clicking the delete button removes everything instead of just one textbox. Can anyone spot the error in my code or offer a solution to remo ...

Ways to troubleshoot setTimeout functioning during HTTP requests?

Utilizing Socket IO in my client app, I have implemented a feature to check for unread events. The process involves making a request to the backend, which then sets a 5-second timeout before checking for any new events and sending them back. // client soc ...

Creating an HTML file using PUG in a local environment (using npm and gulp)

Is there a way to automatically generate an HTML file with the same name as my Pug file whenever I save using gulp? I've checked all the documentation on but it only explains how to return Pug content in console... ...

Is there a way to trigger an Axios response without repeated calls or the use of a button?

As I navigate my way through using react and Axios, I encountered an issue with a get request in my code. Currently, I have a button that triggers the request when clicked, but I want to eliminate the need for this button and instead have the information d ...

How can I ensure that my text input and button are in sync in ReactJS?

I'm currently developing a basic search bar that reads input and updates the 'inputString' state when the content changes. Upon clicking the 'search' button, the inputString is split and assigned to the 'keywords' state a ...

The React JSX error you encountered is due to the missing return value at the end of the arrow function

After implementing my code, I noticed the following: books.map(({ subjects, formats, title, authors, bookshelves }, index) => { subjects = subjects.join().toLowerCase(); author = authors.map(({ name }) => name).join() ...

Dealing with numerous Ajax calls within a single Ajax request

I am utilizing the $http method in angularjs to retrieve multiple "parent" elements. Within the success method of these Ajax calls, I need to loop through the parent elements and make another Ajax call for each parent element to fetch its corresponding chi ...

Prevent title flickering in Android using Ionic

I am attempting to create a tab content page using the "standard" method recommended by the ionic template example. However, I have noticed that when switching between tabs on Android, the view title flickers. This issue is not present on iOS or desktop b ...

Implementing Google Ads Code in NextJS for Automated Units

I'm currently working on a NextJS project and I need to integrate the Google AdSense code for automatic ads. The Google ad code I have is: <script async src={`https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${process.env. ...

The Alert Component fails to display when the same Error is triggered for the second time

In the midst of developing a Website using Nuxt.js (Vue.js), I've encountered an issue with my custom Alert Component. I designed a contact form on the site to trigger a specialized notification when users input incorrect data or omit required fields ...

The art of properly indenting coffee script code

I encountered an indentation error in these lines Are there any online validators that can assist me? showAliveTests : (pageIndex, statusFilter) -> data= pageIndex:pageIndex status:statusFilter $.ajax u ...

What is the best way to eliminate the space between two columns of a row in Bootstrap 5 grid system?

In my quest to achieve the grid layout illustrated in the image below https://i.sstatic.net/4hsjw.jpg .col_1{ background-color: bisque !important; height: 500px; } .col_2 { width: 300px; height: 287px; background-position: cent ...

Unable to transfer HTML code into the TinyMCE editor

I've successfully stored raw HTML content in my database, and now I want to display it in my TinyMCE editor for users to easily edit and submit. Below is the form: <textarea id="postfullOnEditPop" type="text" class="validate" placeholder="Enter f ...

Using Jquery to make an Ajax request to an Asp.net Web Method

My current approach involves using a jquery method to transmit only the member identification # from the client side to the server side. On the server side, I have a traditional Web Method in place to receive the data and execute SQL queries accordingly. ...

What is the best way to notify a user one minute before their cookie expires using PHP and JavaScript?

I need a solution to alert my logged-in users one minute before their cookie expires, allowing them to save content in the CMS. Any ideas on how I can make this happen? In my auth file, I have configured the following: setcookie("USERNAME", $user,time()+ ...