What is the speed of the jscript garbage collector? Rotating Matrices in Three.js

Utilizing these two functions enables me to rotate objects within my three.js scenes:

    // Rotate an object around an arbitrary axis in object space
    function rotateAroundObjectAxis(object, axis, radians) {
        rotationMatrix = new THREE.Matrix4();
        rotationMatrix.makeRotationAxis(axis.normalize(), radians);
        object.matrix.multiplySelf(rotationMatrix);  // post-multiply
        object.rotation.getRotationFromMatrix(object.matrix, object.scale);
        delete rotationMatrix;
    }

    // Rotate an object around an arbitrary axis in world space      
    function rotateAroundWorldAxis(object, axis, radians) {
        rotationMatrix = new THREE.Matrix4();
        rotationMatrix.makeRotationAxis(axis.normalize(), radians);
        rotationMatrix.multiplySelf(object.matrix);        // pre-multiply
        object.matrix = rotationMatrix;
        object.rotation.getRotationFromMatrix(object.matrix, object.scale);
        delete rotationMatrix;
    }

rotationMatrix is a global variable that I utilize. Despite not having encountered any issues thus far, my lack of Javascript and web app development expertise led me to talk to someone who suggested that creating new objects with each function call, particularly since they are called once per frame at times, could pose concerns regarding garbage collection efficiency. Should I worry about the garbage collector's ability to manage this over time? I am aware that the delete keyword functions differently than in C++ as it only removes references. Can using it at the end of each function help alleviate potential issues? Additionally, what other measures can I take to improve the efficiency of these functions, allowing them to be utilized frequently without causing performance degradation or excessive memory consumption by the browser.

Answer №1

Exploring further into this topic, I delved deeper into utilizing the functionalities of the Chrome Developer Tools. Through this process, I optimized and refined the functions to enhance efficiency. While it remains to be seen how well these optimizations will scale, initial profiling indicates improvements in memory usage and garbage collection.

Notably, the function for rotating in world space necessitates a copy to avoid generating a new matrix. Essentially, without creating a fresh matrix with each call, copying the reference alone is insufficient; the entire matrix must be duplicated. The balancing act revolves around determining whether the overhead of this copy or the burden on the garbage collector will prove more costly.

// Efficiently rotate an object around any axis within its object space
var rotObjectMatrix = new THREE.Matrix4();
function rotateAroundObjectAxis(obj, axis, rad) {
    rotObjectMatrix.makeRotationAxis(axis.normalize(), rad);
    obj.matrix.multiplySelf(rotObjectMatrix); // post-multiply
    obj.rotation.getRotationFromMatrix(obj.matrix, obj.scale);
}

var rotWorldMatrix = new THREE.Matrix4();
// Optimal rotation of an object around a specific axis in global coordinates      
function rotateAroundWorldAxis(obj, axis, rad) {
    rotWorldMatrix.makeRotationAxis(axis.normalize(), rad);
    rotWorldMatrix.multiplySelf(obj.matrix); // pre-multiply
    obj.matrix.copy(rotWorldMatrix);
    obj.rotation.getRotationFromMatrix(obj.matrix, obj.scale);
}

Comparing performance between the original functions and the updated ones depicted in new screenshots, a slight improvement is indicated with the revised functions. Personally, discerning a noticeable difference remains uncertain.

UPDATE: Subsequently, upon learning about the updateMatrix function, I devised an alternative approach that eliminates the necessity for replicating the complete matrix. Below showcases the streamlined world rotation function:

/** Applies a radial rotation adjustment to the object's orientation relative to the world axis */
var rotWorldMatrix = new THREE.Matrix4();
function rotateWorldAxis(object, axis, radians) {
    rotWorldMatrix.makeRotationAxis(axis.normalize(), radians);
    object.updateMatrix();
    rotWorldMatrix.multiplySelf(object.matrix); // pre - multiply
    object.rotation.getRotationFromMatrix(rotWorldMatrix, object.scale);
}

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

Store a distinct identifier as an object within a JavaScript collection

I am attempting to save a key as an object in JavaScript by using the Map collection: let tempEntry = {y:y, x:x} let exist = map1.has(tempEntry); if(exist){ map1.set(tempEntry, true) } else { map1.set(tempEntry, false) } However, I am facing an ...

Which callback function is best suited for handling the response in an XMLHttpRequest and rendering it on the webpage?

Upon a user action on the page, an AJAX request is made to my Node.js Express server to send data. Here's what happens next: router.post('/', function(req, res){ //user authentication first, then inside that callback res.redirect('/d ...

JavaScript file encountering a problem with its global variables

What is causing the alert("2") to pop up first instead of it being second? Why am I encountering difficulty creating global variables c and ctx? Is there a way for me to successfully create these two global variables in order to utilize ...

Unable to retrieve custom CSS and JS files hosted on the server

Encountering Server Issue My server is returning a 404 NOT FOUND error when trying to access my static files: css and js. In IntelliJ IDEA, the path appears correct as shown in the image https://i.stack.imgur.com/nTFv9.png. However, upon accessing the pa ...

Verification of radio selections

I have successfully implemented validation for the radio button. Now, I would like to add an alert box that asks "Are you sure you want to pick 'x'?" before proceeding with the code. If the user clicks cancel, they should return to the webpage. B ...

Ways to retrieve the checkbox value using PHP in conjunction with XML

I am currently in the process of learning PHP, XML, AJAX, and other related technologies. I have a form that is working fine for the most part, but I am facing an issue with passing the value/state of a checkbox to my PHP script. It's worth mentionin ...

arranging objects based on the distance between them

Here is a JSON array I am working with: var details = [ { 'address':'Pantaloons,701-704, 7th Floor, Skyline Icon Business Park, 86-92 Off A. K. Road,Marol Village, Andheri East,Mumbai, Maharashtra 400059', 'lat':&apos ...

Create a custom sorting option for an Angular select dropdown menu that is tailored to a specific

<select name="region" id="region" ng-options="id as name for (id, name) in regions[entry.country]" ng-model="entry.region" class="form-control select-styled" required></select> I am looking to implement a filter or custom sort to rearrange th ...

Top method for cycling through an Array in React

I am looking to create a memory game using React for a portfolio project. I have an array of 20 items with 10 different sets of colors. const data = [ // Manchester Blue { ID: 1, Color: "#1C2C5B" }, ...

Performing AJAX requests within AJAX requests without specifying a callback function for success

Upon reviewing this discussion jQuery Ajax Request inside Ajax Request Hello everyone, I'm in need of some clarification on a particular scenario. I recently took over the code from a former member of my development team and noticed that they have ma ...

Tips for packaging a personalized AngularJS Directive with an external HTML template

Take a look at my project structure below project -Lib -MyCustomDirective (to be used in various applications) -customDir.js -customDirTmpl.html -app -js -myfirstcontroller.js -main.js -partials -myfirstview.html ...

What could be causing an error with NextJS's getStaticPaths when running next build?

When attempting to use Next.js's SSG with getStaticPaths and getStaticProps, everything worked fine in development. However, upon running the build command, an error was thrown: A required parameter (id) was not provided as a string in getStaticPath ...

Verify whether a string includes any of the elements within an array

Imagine I have a string: const subject = "This process is flawless" and an array: const matchArray = ["process","procedure","job"] If subject contains any keyword from matchArray, I want to do the following: if (su ...

Navigating to a webpage using the href attribute in JavaScript

Due to specific design constraints, I am unable to wrap elements with an Anchor tag. However, I can implement a click event on those elements. How can I navigate to the link correctly? The code snippet from before: <a href="Page1.html"> <but ...

Transform the array into several different arrays

Having some trouble manipulating this array to get it into the desired form. This is the initial array: const children = [ { type: 'span' }, { type: 'br' }, { type: 'span' }, { type: 'br' }, { type: ' ...

Develop a JSON object with a unique format by combining elements from two separate arrays using JavaScript

I've searched extensively on stack for a solution but couldn't find one, so I'm reaching out here for help: Let's consider two arrays: one with "keys" and the other with "values" For example: keys = [CO2, Blood, General, AnotherKey, . ...

What could be causing this error in a new Next.js application?

After multiple attempts, my frustration and disappointment in myself are causing a headache. Can someone please assist me? I am trying to create an app using the following command: npx create-next-app@latest --ts Immediately after running next dev, I enco ...

Incorporating Paged.JS functionality into a React/JS web application

My attempt to showcase my html page using paged.js in a react project has hit a snag. The html loads perfectly when accessed from local host (not via npm start, but the live server extension on vscode). However, following the steps outlined on this website ...

Achieving the retrieval of all data can be done simply by utilizing the `echo json_encode($data);

I am trying to automatically update the user wall with new data from the database using a script that checks for updates every 15 seconds. Everything works fine when I only use one piece of data like $data = $row['description']; in the server.ph ...

Exploring the differences between using a local controller in Angular's MdDialog modal versus displaying a shadow at

I've been attempting to utilize an app-level controller to showcase a modal dialog. The local function controller tests are functioning flawlessly, but the app level controller is only showing a grey shadow instead of the expected dialog. The edit an ...