Issue with memory leak in Three.js r89 when using STL models

I'm struggling with a webpage I'm constructing. It seems like a simple task, but I keep encountering issues that I suspect may be caused by a memory leak.

Despite spending most of the day researching for a solution, I can't seem to find one. I've followed all the advice I could find, but I'm still stuck.

I have 30 STL models, each under 120kb, that I switch between. Only three are displayed on screen at once and users can customize the entire model by swapping them out.

To change the colors of the models, I use:

var selectedObject = scene.getObjectByName(object);

newMaterial = '#'+matHex[newMaterial-1];
newMaterial = hexToRgb(newMaterial);

selectedObject.material.color = newMaterial;

This part works smoothly without any noticeable slowdowns.

For replacing the model, I use:

var mesh = scene.getObjectByName(object);

if (mesh instanceof THREE.Mesh)
{
    scene.remove(mesh);
    mesh.geometry.dispose();
    mesh.geometry = null;
    mesh.material.dispose();
    mesh.material = null;
    mesh = null;
}

Afterwards, I execute a function to add the model back into the scene:

function addHandle(){
    loader.load( stlPath+'Handle'+handleID+'.stl', function ( geometry ) {
    material = '0x'+matHex[handleMat-1]; //set color hex from array

    var handleMaterial = new THREE.MeshPhongMaterial( { color: parseInt(material), specular: specular, shininess: shininess } );
    var handleMesh = new THREE.Mesh( geometry, handleMaterial );

    handleMesh.position.set( 0, 0, 0 );
    handleMesh.rotation.set( Math.PI/2, - Math.PI/2, 0 );
    handleMesh.scale.set( .008, .008, .008 );
    handleMesh.name = "Handle";
    handleMesh.id = handleID;
    handleMesh.castShadow = true;
    handleMesh.receiveShadow = true;
    scene.add( handleMesh );

    updateHandle(); //check if Handle needs to rotate
    } );
}

Based on my research, this is the correct method for disposing of meshes. However, after processing around twelve meshes in this manner, the camera rotation starts to slow down and loading the next model takes longer. This lag becomes especially noticeable on mobile devices.

If anyone spots something obvious that I might be overlooking, I would greatly appreciate the help!

Answer №1

Upon investigation, I realized that the issue was caused by my own mistake, just as I had suspected. It turns out that I was invoking animate(); every time a model was replaced, which was causing performance issues. After removing those calls, the program is now running significantly smoother. I will provide an update if the problem resurfaces!

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

What is the alternative way to add an object to React-Three outside of using componentDidMount?

I have been experimenting with React samples for Three.js and I'm struggling to figure out how to add an object (mesh, geometry) outside of the componentDidMount lifecycle method. I've attempted to introduce new objects, dispose of previous ones ...

Problems with Wordpress AJAX search functionality

I am currently working on implementing a search feature using AJAX to dynamically load posts. However, I am facing an issue where the results are not being displayed. This code snippet was adapted from another source and modified based on private feedback ...

Angular date selection with a range of plus two days, factoring in the exclusion of weekends

I am currently using a mat date picker range with specific logic. The minimum date that a user can select on the calendar is set to + 2 days. For example, if today's date is July 20, 2022, the minimum selectable date would be July 22, 2022. However, ...

When combining Socket.io 1.0 with express 4.2, the outcome is a lack of socket connection

According to the title, I am attempting to integrate socket.io 1.0.4 with express 4.2, but all requests with "/?EIO" are resulting in a 404 error. Below are my file configurations: ./bin/www : #!/usr/bin/env node var debug = require('debug')(& ...

Having Trouble with Axios PUT Request in React and Redux

I'm having trouble making a PUT request to the server. I understand that for a PUT request, you need an identifier (e.g id) for the resource and the payload to update with. This is where I'm running into difficulties. Within my form, I have thes ...

Supabase authentication in a React app is causing a TypeError: Unable to access properties of undefined (specifically 'user')

In the development of my React application using Next.js, I've integrated Supabase for authentication. I've created a custom hook named useAuthentication to verify if the user is logged in and redirect them to the login page if they're not. ...

Develop a feature within a standard plugin that allows users to add, remove, or refresh content easily

I have developed a simple plugin that builds tables: ; (function ($, window, document, undefined) { // Define the plugin name and default options var pluginName = "tableBuilder", defaults = { }; // Plugin constructor func ...

Is it possible that JavaScript isn't functioning properly?

My current issue involves echoing JavaScript from a PHP file to an HTML page using AJAX. Strangely, the JavaScript does not run when dynamically echoed, even though it appears in the Inspect Element tool. On the other hand, purely textual content echoes su ...

Learn how to implement a call to 'next()' in Express and Node.js only after successfully creating schemas

I am currently developing an event app, and within my 'Event' schema, I have an array of 'Tag' schemas, allowing each event to be associated with one or more tags. Event: var EventSchema = new Schema({ ... tags: [{ type: Schema.Type ...

"JavaScript's versatility shines through with its ability to handle multiple variables

Presently, I am working with the following script: <v-tab :title="siteObject.xip_infos[index].lineid" > <div class="description text-left" :class="{ 'text-danger': item.status === 'DEACTIVE' }"> <small v-for="(f ...

What are the steps to integrate dynamic data into chartjs?

Can you assist me in understanding how to dynamically populate Chartjs with data from a json file? Specifically, I am looking to dynamically fill the labels and data fields. Sample JSON File <<< [ { "EFICAZ_TAB_ITEM_ID":1, " ...

Setting up the react-ultimate-pagination component

I've been experimenting with the react-ultimate-pagination package available at: https://github.com/ultimate-pagination/react-ultimate-pagination My goal is to configure it in a way similar to their basic demo showcased here: https://codepen.io/dmytr ...

Improving Performance in Vue by Reducing `$set` Usage

Sharing my code snippet below <div v-for="namespace in chosenNamespaces" v-bind:key="namespace.id"> <!-- Select the Parameter --> <select @change="updateParameter($event, namespace.id)" v-model="currParameterValues[na ...

Track the status of an extensive MySQL query using PHP

Looking for a way to show the progress percentage of a lengthy mysql query using php? Well, you can create a filter button in your database that triggers a javascript function through ajax and calls a php file. function show(){ $.ajax({ ...

What is the best way to merge different Vue JS instances (each linked to different html divs) into one cohesive unit using Vue

Essentially, I have a scenario where I've created two HTML divs named vueapp1 and vueapp2. Both of these divs serve the same purpose of displaying information and are linked to their individual Vue instances for extracting JSON data and presenting it. ...

Determine the necessary camera zoom level to ensure the object fits within the height of the screen

In my Three.js project, I've been utilizing these formulas to determine the visible width and height: var vFOV = camera.fov * Math.PI / 180; // converting vertical fov to radians var height = 2 * Math.tan( vFOV / 2 ) * dist; // calculating vis ...

Performing operations on objects in Javascript/Jquery: The alternative to .every()

Is there a way to efficiently test for empty values in an array or object before proceeding? I want to check if all the items in a query object are blank before sending it out. While I could use a simple for loop, I'm curious if there's a more co ...

Transitioning from Chrome's USB App API to the Web USB API

My current challenge involves migrating my API from a Chrome App to a Progressive Web Application due to the deprecation of the platform. I need to retain USB support in my web platform application, and someone recommended utilizing the Web USB API. Howev ...

Removing an article from a Vue.js localStorage array using its index position

I am facing an issue while trying to remove an item from localStorage. I have created a table to store all the added items, and I would like to delete a specific article either by its index or ideally by its unique id. Your assistance is greatly apprecia ...

`Can controllers be included in route or template definitions?`

When it comes to defining a route with a template, there are two main ways to set the controller for the view: In the route: $routeProvider .when('/phone/:phoneId', { controller: 'PhoneDetailController', templateUrl: &ap ...