liberating RAM in three.js

My application is loading a large number of meshes. When I try to dispose of old meshes to free up memory, it seems the memory is not actually being released. Am I missing something?

Here is a simple example to reproduce the issue:

  1. Load 100 large binary meshes
  2. Dispose of all the meshes
  3. After disposal, Chrome task manager shows that 250mb of memory is still being used, the same as before step 2.

    memtest

    var scene = new THREE.Scene();
    var mymesh=Array();
    
    // 1. Load a lot of geometry/meshes...
    
    for(var i=0;i<100;i++)
    {
        var bloader;
        bloader = new THREE.BinaryLoader();
    
        bloader.load( "objekte/presto_6.js" , function( geometry ) 
        {
            mymesh.push(new THREE.Mesh( geometry, new THREE.MeshBasicMaterial( {color:0xffffff } ) ));
            scene.add(mymesh.length-1);
        });
    }
    
    // 2. Try to dispose objects and free memory...
    
    for(var j=0;j<mymesh.length;j++)
    {
        mymesh[j].geometry.dispose();
        mymesh[j].material.dispose();
        screne.remove(mymesh[j]);
    }
    
    mymesh=Array();
    
    </script>
    

Answer №1

Seems like a small mistake, but just in case: screne.remove(mymesh[j]); should actually be scene.remove(mymesh[j]);

Aside from that, remember to understand how JavaScript handles memory. Its garbage collector works by flagging objects that are no longer referenced and cleaning them up during the next garbage collection cycle:

for(var j=0;j<mymesh.length;j++)
{
    mymesh[j].geometry.dispose();
    mymesh[j].material.dispose();
    scene.remove(mymesh[j]);
}

The mymesh array still holds references to the mesh objects you are trying to release. The garbage collector sees these references and doesn't flag the objects for removal. To free up memory, consider reassigning or deleting the unnecessary keys in the array:

for(var j=0;j<mymesh.length;j++)
{
    mymesh[j].geometry.dispose();
    mymesh[j].material.dispose();
    scene.remove(mymesh[j]);
    mymesh[j] = undefined;//or
    delete(mymesh[j]);
}
//or simply:
mymesh = undefined;//or another value

This will release the memory, unless there are other variables referencing these objects as well.
Also, avoid using Array() as it is considered bad practice in JavaScript. Constructors should be used with the new keyword, but it's recommended to use array literals instead for simplicity:

mymesh = [];//an array literal
//example of unexpected behavior:
mymesh = new Array(10);//[undefined, undefined, undefined....]
mymesh = [10];
mymesh = new Array('10');//['10']
mymesh = new Array(1.2);//RangeError
var o = new Object(123);//returns new Number
o = new Object('something');//new String
o = new Object(false);//new Boolean
o = new Object('foo', 'bar');//new String('foo')!!!
o = {foo: 'bar'};//<-- a simpler way to create an object

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

How to troubleshoot Path Intellisense in VScode when using jsconfig.json for Next.js

In the structure of my project, it looks like this: jsconfig.json next.config.json components |_atoms |_Button.jsx |_Button.module.scss |_... |_... ... Within the jsconfig.json file, I have specified the following settings: { ...

When trying to access the same path, useEffect does not trigger

I integrated the API to execute when the screen is loaded using useEffect in Next.js v10. The code implementation is straightforward: ... const fetchAPI = async () => { try { await axios.get({ .... }) } catch (e) { console.error(e) } } R ...

Using animation.width() in Javascript to create a countdown

Currently, I am working on creating a visual countdown for my users to indicate when an animation will finish. The code snippet below shows my initial attempt: function setClassAndFire(){ timer = setInterval(function () { t--; ...

Choose a portion of the content within a div element

In my SVG element, I have created a foreignObject with a textarea and a div inside. The textarea is transparent and lies on top of the div. As users type in the textarea, the text gets copied to the div creating a WYSIWYG editor. Everything functions corre ...

Running a 2D JavaScript game script on a React page - A step-by-step guide!

I am facing a challenge with my website that features a game coded entirely in javascript. Despite my efforts to switch the site from an HTML layout to a more modern React design, I can't seem to get the game to display correctly. In the original HTM ...

Unable to consistently select a radio button via code across different browsers

Is there a way to automatically select a radio button based on the URL path? $(document).ready(function () { function checkRadioBasedOnUrl() { var urlPath = window.location.pathname.split("/"); console.log(urlPath); // ["", "tradeshow ...

Displaying the product quantity counter in the shopping cart immediately after adding the item

My website has a shopping cart quantity counter that doesn't update immediately when a product is added. Instead, it requires a page reload or navigation to another page for the change to be reflected. I would like the quantity counter to show the pro ...

Switching from "Straight Quotes" to "Curly Quotes"

Looking for a solution to convert regular straight quotes into curly quotes in a Javascript-based rules engine application. Rather than just using a simple string.replace for ["], I need a method that will insert the correct curly quote depending on its po ...

At what point is it necessary to generate a new vertex array object when sketching numerous objects?

I'm embarking on a game development project using WebGL. Currently, I have three textures in my arsenal- one for letters used in the font, another for character sprites, and a tilemap texture for the world. With these large textures at hand, I find m ...

Dealing with empty POST request bodies in Node.js Express is a common challenge

In my Node.JS project using Express framework, I am encountering an issue while trying to access the body of a POST request. The POST request is being sent through an HTML form, and upon checking with WireShark, I can see that the request is indeed getting ...

Stop the Sidebar from showing up on certain pages with Next.js

Currently, I am facing a small issue with my application. The problem lies in the sidebar that appears on my login.jsx page when I specifically do not want it there. However, I would like it to appear on all other pages except for this one. Is there a cond ...

Generating a JSON outcome from a SQL server database

My SQL server has the following table layout: Table ( id int, title varchar(40), start Date(), end Date(), allDay bool, username varchar(40) ); I found some code on this blog to create a JSO ...

Tips for creating a hover-activated dropdown menu

How can I create a drop-down menu in my horizontal navigation bar that appears when hovering over the Columns tab? The drop-down menu should include options such as Articles, Videos, Interview, and Fashion. To better illustrate what I am looking for, here ...

What are the most effective ways to manage state in form components using React?

As I delve into the realm of best practices for managing state in React components, I find myself grappling with different approaches. Initially, I crafted a form by creating a TextField component structured like this: var TextField = React.createClass({ ...

The CSS styling is not being rendered correctly on the AngularJS HTML page

Encountering a puzzling situation here. Our angular controller is successfully delivering data to the page, but we are facing an issue with rendering a table due to an unknown number of columns: <table border="1" ng-repeat="table in xc.tables"> ...

Is it possible to directly add a child in HTML from nodejs?

I'm in the process of developing a chat application that requires users to select a room from a list of available rooms stored in <datalist> options, which are fetched from a SQL table on the server. Within my login.html file, users are prompte ...

What are the risks of using react + bootstrap without importing bootstrap.js?

When bootstrap library is used along with React, potential unpredictable behavior and difficult bugs may arise due to DOM modifications. Is it feasible to use bootstrap without including bootstrap.js? What are the drawbacks? While I am aware of the ' ...

Using JavaScript, the list of items (images) will be displayed and placed into HTML panels

Below is the layout structure on my website: <div class="panel-heading"><h3 class="panel-title">Suggestions</h3></div> <div class="panel-body"> <div class="col-md-7"> <h3><span class= ...

What could be causing the error with firebase Sign In in next.js?

I set up a sign in page to enter email and password for Firebase authentication. The sign up process works fine, but I'm encountering an issue with the sign in functionality. 'use client' import { useState } from 'react'; import { ...

What is the best way to declare a variable within a VueJS v-if condition without it being visible?

In my code, I have a specific template that is displayed when a certain condition is met using a v-if statement. In this template, I need to set a variable to N/A, but I am struggling with how to accomplish this simple task. <span v-if="se ...