Should you avoid generating a new array within a loop in Javascript?

At times, using a temporary array in a loop to store data becomes necessary. This is especially useful when dealing with 2-dimensional arrays. However, the question arises - is it considered bad practice to create a new array in a loop, especially if this action needs to be repeated frequently, like in animations?

for (let i = 0; i < 10000; i++) {
    const temp = [];
    for (let j = 0; j < 10; j++) {
        temp.push(j);
    }
    arr.push(temp);
}

If the use of a variable is intended, one could opt for employing a global variable and assigning values to it repeatedly. Attempting to clear the array by setting temp.length = 0 may lead to unexpected outcomes since the array's reference is stored, causing all data to become the last pushed values. Another attempt was made using a global const temp = new Set(); however, pushing the temp set into the arr array required arr.push([...temp]). Therefore, is creating a new array in such situations unavoidable?

Answer №1

Benefits of Typed Arrays

TypedArrays are highly recommended when it comes to creating arrays due to their superior performance and memory advantages compared to standard arrays.

If you need to quickly create an array of numbers, consider the following code snippet:

var i,j,b,a = [];
for (i = 0; i < 100000; i += 1) {
    a[i] = b = new Float64Array(10);
    for (j = 0; j < 10; j += 1) {
        b[j] = j;
    }
}

This benchmarked at 634, which is 5.5 times faster than the fastest Array method:

var i,j,b,a = [];
for (i = 0; i < 100000; i += 1) {
    a[i] = b = [];
    for (j = 0; j < 10; j += 1) {
        b[j] = j;
    }
}

Which resulted in a benchmark value of 3664, 3.4 times quicker than:

const arr = [...Array(10000)];
for (let i = 0; i < arr.length; i ++) {
  arr[i] = [...Array(10).keys()]
}

That particular method had a benchmark score of only 12352.

Typed arrays have fixed sizes and are pre-filled with zero upon declaration. They do not become sparse and can help eliminate garbage collection overheads if used correctly.

Additionally, by using Atomics and SharedArrayBuffers, you can share typed arrays with workers, providing true sharing as shared arrays have a single address.

While typed arrays are limited to Doubles, floats, signed and unsigned integers, they can accommodate any type of data and significantly improve performance for various array operations, considering that computers fundamentally process data in binary form.

Are Loops for Creating Arrays Inefficient?

There is nothing inherently wrong with creating arrays within loops. As demonstrated earlier, utilizing efficient array creation methods like typed arrays can result in significant performance improvements.

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

Attempting to establish a means to switch between languages

Currently, I am in the process of implementing a language switch feature for a website project that I am currently working on. This feature will allow users to seamlessly switch between English, Latvian, and Norwegian languages. To achieve this functionali ...

Why is my JavaScript method not working and throwing an error?

Attempting to streamline my code by creating a separate method for calling an ajax function in multiple places. When I try to use the separate method instead of calling it directly, it doesn't work as expected. data: columns[5], type: 'a ...

socket.io, along with their supporting servers

Can socket.io function separately from being the webserver? I prefer to utilize an external webserver, but in order for it to function properly I require /socket.io/socket.io.js. Is there a method other than duplicating[1] this file? I want to avoid comp ...

Alter the ng-repeat values that are dynamically added from a common source

I am facing an issue where dynamically added ng-repeat values are being changed across all divs instead of the selected one. In my code below, clicking on dynamically appended divs shows a form on the right side allowing input text fields. However, I want ...

Is this jQuery script not functioning properly?

I came across this code on jsfiddle, and I really want to incorporate it into my PHP file. However, when I tried to do so, it didn't work even though I simply copied and pasted the code without making any changes. Here is my code: <!DOCTYPE html& ...

What is the benefit of storing an IIFE in a variable?

When it comes to using IIFE in JavaScript and AngularJS, I have come across two common structures: Structure 1: //IIFE Immediately Invoked Function Expression (function () { }()); However, there is another structure where the IIFE is assigned to a var ...

Despite the correct value being displayed in the console.log, the Textfield is not responding to the Reducer

I am currently working on a project to create a tool that can iterate through the pupils of a school class. In order to achieve this, I have implemented a text field in a react component that displays a value: <input className="form-control" onChange={ ...

Save the modal to a variable and display it when clicked

I am trying to create a modal and display it when a user clicks a button. However, I seem to be facing an issue where nothing happens when the button is clicked and there are no errors in the console. $( '.outlet' ).on('click', functio ...

Utilize dot notation to access elements in a multi-level array

I am interested in creating a class that can access multidimensional arrays using dot notation: $config->get('bar.baz.foo'); Instead of the traditional way like this: $config['bar']['baz']['foo'] Here is the i ...

Can JavaScript be used to dynamically update drop down lists in a gridview?

My gridview has multiple fields including PreviousPoints, GainedPoints, and TotalPoints. In edit mode, PreviousPoints is not editable, GainedPoints is a dropdown list, and TotalPoints is also a dropdown list. Whenever the selected value in GainedPoints ch ...

Having trouble uploading big files on your Windows system?

My challenge is to successfully upload a large file using Angular. Specifically, I am attempting to upload a Human Genome tar file, which is a minimum of 2.5gb in size. Strangely, when I try to upload the file from Linux using any browser such as Chrome or ...

Tips for transferring variables between two browser windows within the same session of Internet Explorer 11

Is there a way to prevent a parameter from displaying in the address bar and avoid storing it locally? For example, the parameter value is like vndfj/dfgdgdfg12/dg==. I attempted the following code, but it does not work on IE and Edge browsers: let data ...

What is the best way to reset form after submission in Next.js?

I have a contact form and I want all the form values to be cleared after submitting the form. I've tried the following code, but the values of the form remain unchanged after submission. What could be causing this issue and how can it be resolved? ...

Scroll horizontally through the number field in Chrome

I have configured a number input field with the text aligned to the right. Scenario: While testing, I discovered that selecting the entire text or using the middle mouse button to scroll within the input field allows for a slight leftward scrolling of ab ...

Trouble with displaying an array of React elements in the render() function

While learning React by creating sample projects with Meteor, I've managed to grasp the basics but hit a wall. I'm utilizing a Twitter API to fetch the latest three tweets from the BOINGBOING Twitter page. The API is functional, and I can succes ...

css / Chrome is not displaying the correct background size

After experimenting with various CSS properties, I still can't get my background image to stay fixed on the browser screen without any scrolling. For better understanding, I have attached an image below: https://i.sstatic.net/ieCZN.jpg Below is my C ...

Alert Ajax/Javascript when the background PHP operation has finished

Here's the scenario - straightforward and concise : On Page A : An ajax request is made (to intermediate.php) which triggers a background process - let's call it back.php interm.php responds back.php continues its operation until completion, wh ...

What is the method to enable Google Adsense to reach pages within a restricted login area that utilizes JSON authentication?

I am looking to place Google Adsense ads on my website, but I want them to only appear within a specific area that is accessible to users after they log in. Within the Google Adsense interface, I have explored the Account Settings -> Access and authori ...

Click on the canvas to fill a specific area with JavaScript

My goal is to implement a JavaScript function that will shade specific areas of canvas drawings when clicked. Below is the code I have that draws a square inside a circle. <!DOCTYPE HTML> <html> <head> </head> <body&g ...

Using jQuery to create a drop-down menu

I currently have a table filled with data. Whenever a user clicks on a cell within a specific column, I would like it to transform into a select dropdown menu. This dropdown menu will allow the user to choose a category for that particular row. The selecte ...