Quick method to populate an array with elements

I need to populate an array with a large number of objects. Currently, my approach looks like this:

let useVertices = [];
const len = this.indices.length;
for(let i = 0; i < len; i++){
    let index = this.indices[i]*3;
    useVertices.push(new THREE.Vector3(
        this.vertices[index],
        this.vertices[index+1], 
        this.vertices[index+2])
    );
}

this.indices is an Int32Array that contains nearly 4 million elements. this.verticesis a Float32Array with around 650,000 elements.

The current implementation usually takes between 500 and 800 ms to complete.

I am using CefSharp as the browser since the website is running within a C# application.

Are there any ways to optimize this code for faster performance?

Answer №1

Compiling what I believe to be the top suggestions from the responses (excluding challenges to the original idea) awaiting your experimentation:

  • Ouroborus mentioned that with 4M indices and only 650k vertices, you may end up creating redundant instances of THREE.Vector3. Reusing instances by storing previous ones based on index is a possible optimization.
  • Gabriele Petrioli suggested using assignment instead of push to avoid an extra method call: useVertices[i] = ___
  • Prior allocation of the array can be done using new Array(len)
  • To minimize unnecessary property lookups, cache indices, vertices, and THREE.Vector3
  • If possible, declare useVertices as const
const { indices, vertices } = this;
const V = THREE.Vector3;
const len = indices.length;
const useVertices = new Array(len);
const vectors = new Map(); // For reusing vectors
for (let i = 0; i < len; i++) {
    let index = indices[i] * 3;
    let vector = vectors.get(index);
    if (!vector) {
        vector = new V(
            vertices[index],
            vertices[index + 1],
            vertices[index + 2]
        );
        vectors.set(index, vector);
    }
    useVertices[i] = vector;
}

(Please note: Plat00n attempted to use an array in place of a Map earlier, but even with the inclusion of the get and set method calls, the Map proved to be more efficient.)

Answer №2

One efficient method is the Vectorized approach

  • To optimize performance, utilize typed arrays (Float32Array) directly for useVertices instead of adding elements one by one.

  • Implement vectorized operations such as slice and copy to manipulate these typed arrays, avoiding the need to iterate through individual elements.

  • Take advantage of built-in vectorized functions in Three.js like Vector3.fromArray for a direct conversion from the vertices array to useVertices.

     // Create typed array directly
     const useVertices = new Float32Array(this.indices.length * 3);
    
     // Copy data by traversing indices
     for (let i = 0, j = 0; i < this.indices.length; i++, j += 3) {
       const index = this.indices[i] * 3;
       useVertices.copyWithin(j, this.vertices, index, index + 3);
     }
    
     // Alternatively, use Vector3.fromArray  
     const useVertices = THREE.Vector3.fromArray(this.vertices, 
     this.indices);
    

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

Create a toggle effect similar to jQuery using JavaScript

Looking for pure JavaScript code to implement show/hide functionality similar to jQuery. Currently, I am using the following code: y=document.getElementById('regform').style.display; if (y == 'block'){ document.getElementById(&apo ...

Material Angular table fails to sort columns with object values

Currently, I am in the process of developing a web application using Angular Material. One of the challenges I have encountered is displaying a table with sorting functionality. While sorting works perfectly fine on all columns except one specific column. ...

Interacting with an iframe element using Selenium in Python

I have a webpage with an iframe embedded, and I'm using Selenium for test automation: <iframe class="wysihtml5-sandbox" security="restricted" allowtransparency="true" frameborder="0" width="0" height="0" marginwidth="0" marginheight="0" style="dis ...

Unable to execute a JavaScript function when triggered from an HTML form

This is the code for a text conversion tool in HTML: <html> <head> <title> Text Conversion Tool </title> <script type="text/javascript"> function testResults(form) { var str = form.stringn.value; var strArray = str.split(" ...

React snap scrolling feature is not working as intended

I've been attempting to implement the snap scroll feature in my react app, but I'm facing issues with it. The regular CSS method doesn't seem to work well in Chrome, as discussed in this Scroll Snap Skips Section on Smaller Screen - Chrome t ...

Submitting a POST request to paginate and sort the results

Currently, I have a system in place where a GET request is used to query the database and display the results. While this method works well, I am looking to transition it into a POST request. This would allow for a more flexible approach by handling JSON b ...

A little brain teaser for you: Why is this not functioning properly on Google Chrome?

Have you noticed that the code below works perfectly in Firefox, but fails in Chrome when trying to 'post' data? $("a").click(function() { $.post("ajax/update_count.php", {site: 'http://mysite.com'}); }); Hint: Make sure you are us ...

A step-by-step guide to adding an object to an already existing array in Vue.js

Within the code snippet below, I am dealing with an object value and trying to figure out how to push it to an existing array. methods: { onChange(event) { this.newItems.push(event.target.value); console.log(event.target.value); } } Here is m ...

Tips for locating and substituting a string in Javascript

Is there a way to locate a particular word within a string and substitute it using JavaScript? For instance Here is a lengthy sentence I want to locate the word "sentence" and modify it to "phrase", resulting in: Here is a lengthy phrase ...

How to retrieve data as an array using a promise in an Express application with React and

After including an array in the return statement, everything seems to be functioning correctly with dispatch and rendering in reducer-items.js. However, there is a discrepancy when I update the data as it does not reflect the changes made. export defa ...

Error 9 in Firebase: The function 'initializeApp' could not be located within the 'firebase/app' module

Since updating to firebase 9, I've been encountering issues with importing certain functions that were working fine on firebase 8. I've gone through the documentation and made necessary code improvements, but the error persists. This issue is not ...

Listening for server updates with jQuery

I am currently working on a web application that communicates with a server for database updates. The issue I am facing is that the update process can vary greatly in time, ranging from milliseconds to tens of seconds for larger updates. I would like to im ...

Utilize Next.js and GSAP to dynamically showcase images upon hovering over the title

I have a dynamic list of titles that I want to enhance by displaying images when hovering over each title. The issue I'm facing is that when I hover over one title, all the images display at once. As a React beginner, I believe the solution should be ...

How to activate a single element within a React array

I am currently working on developing a comment system similar to the one found on YouTube. In my setup, when I click on modify, all comments turn into input fields, but only the selected input should be modified. How can I trigger only the element I clicke ...

Form featuring a mandatory checkbox that must be selected in order to proceed; failure to do so will result in an

So here’s the situation: I have a form with a checkbox for agreeing to the terms of service, and I want to make sure it is checked before proceeding with the donation process. I only have the HTML code and no idea how to implement this functionality. Ide ...

Looking for a way to limit the number of characters allowed per line in a textarea using jQuery

I have the following HTML textarea: <textarea name="splitRepComments" cols="20" rows="3" ></textarea> I have implemented a maxlength restriction using jQuery with the following function: var max = 100; $('#splitRepComments').bind(" ...

Position the Material-UI AppBar and Tab on the far right of the screen

I am trying to achieve a specific layout where the Links for "Homepage Login Settings and etc.." are placed at the right edge of the AppBar, while keeping the "Website" aligned to the left edge of the screen. Here is what I have: https://i.sstatic.net/Wvo ...

There was an issue with retrieving the image URL from the source, causing an error message to display: "

I encountered an error while trying to access my product. Here is the error message https://i.stack.imgur.com/fTmL0.png It seems that the image URL from the sanity database cannot be rendered, even though it worked fine in the tutorial I was following. I ...

Leverage the power of Laravel and ReactJS to beautifully display images

Currently, I am working on a project where I am incorporating ReactJS into a Laravel blade file. To get started, I included the React CDN and began writing code within the script tag. Everything seems to be going smoothly so far, however, I have encountere ...

Unsupported file format for Three.js FBX Binary model

I am currently working with three.js in a mobile application that is built using JavaScript. I am trying to incorporate a 3D model using an .fbx file, but I am facing issues with the binary format not being supported by FBXLoader. As someone who doesn&apos ...