What's the quickest method for duplicating an array?

What is the quickest method for duplicating an array?

I wanted to create a game, but I found that Array.filter was performing too slowly, so I developed a new function:

Array.prototype.removeIf = function(condition: Function): any[] {
    var copy: any[] = Array.from(this);
    var startIdx = 0;
    for (var i: number = copy.length; --i; ) {
        /** i; */
        if (condition(copy[i])) {
            copy[i] = copy[copy.length - 1];
            startIdx += 1;
        }
    }
    copy.length -= startIdx;
    return copy;
}

If used without Array.from, this technique can remove 99999999 elements in just 130 - 295ms, as it simply moves the element to be deleted to the end of the list and then slices it out. Even filtering takes 670 - 1330 ms.

However, when I tested Array.from:

var timeit = new TimeIt(); TimeIt.set();
var range = Array.from(arr) // 'arr' is an Array containing 99999999 elements
timeit.print(); // 1320 - 1634ms

Why does Array.from perform so poorly? It's 10 times slower than 'removeIf', and even slower than Array.filter. Are there any speedier methods for copying arrays?

Answer №1

Let's be honest, when it comes to game development, JavaScript may not be the best programming language choice. If you find yourself needing to manipulate a large array in less than 300 milliseconds, there might be a better approach. However,

You could always create your own solution by creating a loop that iterates through each element and adds it to a new array. Here's a quick example:

let arr = new Array(99999999); 
let newArr = []; 
for(let i = 0; i < arr.length; i++) {
    newArr.push(arr[i]); 
}

This code simply loops through each element and adds it to the new array until all elements have been processed.

Alternatively, you could simplify it with:

let arr = new Array(99999999); 
let newArr = arr; 

Both methods should work, although their efficiency may vary. This is just one of the faster solutions I can think of. I hope this helps :)

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

Freezing Columns and Rows for a Spacious Scrollable Table

After extensive effort, I have been diligently striving to create a solution that allows a table's column headers to scroll with the body horizontally and the first column to scroll with the rows vertically. While I've come across solutions that ...

Creating separate UI-views using ui-router within a single module

Can two independent ui-views be created using ui-router for a single module? The objective is to have the ui-views "know" where to display the current state, essentially creating a form of redirection. https://i.sstatic.net/OTNNL.png ...

What is the correct way to define types for higher-order class components in TypeScript?

I have developed a utility function that currently has an unused options parameter, and it returns a higher-order component wrapping function. How can I effectively define types on the component so that users of the wrapped component can visualize the typ ...

How can I retrieve the chosen value from an AJAX combobox using JavaScript in an ASP.NET C# application?

How can I retrieve the selected value from an AJAX combobox item using JavaScript in ASP.NET C#? Below is the code snippet: <asp:ComboBox ID="dropdown_dest" runat="server" Width="90%" onfocusout="blurFunction()" AutoCompleteMode="SuggestAppend" CssCla ...

Is there a way to convert a PHP array into a JavaScript object and return it?

When I have an array defined and encode it using json_encode() $array = array("a" => "element1", "b" => "element2"); echo json_encode($array); The usual JSON output is: {"a":"element1","b":"element2"} However, my interest lies in getting this out ...

Module request: How can I save the gathered cookies as a variable?

library: https://www.npmjs.com/package/request I am attempting to simultaneously log in with multiple accounts on a website. To manage each session effectively, I plan to create an object where I will store the cookies associated with each account. Now, ...

Navigate to a new page on button click using Row with Tanstack / React-Table and Typescript (2339)

Encountering a linting error when attempting to navigate to a new route by clicking on a table row. The functionality is working but how can I resolve this issue? It's showing an error message stating "The property "id" for type TData does not exist." ...

problem decoding json data from external server

I have a custom Grease Monkey script that is responsible for collecting data from a game and sending it to my server for tracking our team's progress. This process involves multiple Ajax requests between the GM script and the game, followed by sending ...

Inquiring about a particular key-value in a buffer variable in GoLang

Within my code, I have a variable buffer that holds a collection of key-value pairs in an array format like this: [{"Key":"area1", "Record": {"name":"belfast","type":"surburban","v ...

Steps for showcasing a automated slideshow

I'm currently working on creating a slideshow that automatically displays multiple images. While the first image shows up just fine, it doesn't seem to transition to the next one. var currentSlide = 0; displaySlides(); functio ...

Translating a few lines of JavaScript into C#

I'm looking to convert some code from JavaScript to C#, but I'm having trouble grasping a certain section... function getHisto(pixels) { var histosize = 1 << (3 * sigbits), histo = new Array(histosize), inde ...

Tips for setting a value in $scope within an ng-repeat loop in AngularJS

I'm currently facing an issue with ng-repeat in angularJS, specifically on how to assign a value in $scope inside ng-repeat. Here is my scenario: I have a JSON file that contains all the data structured like this: [ {BookID:1,Chapter:1,ContentID:1, ...

Transferring JSON data using DWR (Direct Web Remoting)

Utilizing DWR for AJAX calls in my project involves the conversion of JavaScript objects to Java objects by analyzing the Java class. My goal is to send and receive a JSON-like structure through DWR. For example: JavaScript Object: { "name" : "TamilVe ...

Obtain the value of an element from the Ajax response

Just starting out with Jquery and Ajax calls - here's what I've got: $(document).ready(function () { $.ajax({ type: "GET", url: "some url", success: function(response){ console.log(response); } }) }); Here's the ...

Autoplay feature on Ionic 3 dynamic image slider pauses when manually sliding images

When I retrieve image slider data from a provider's REST API, the autoplay feature works perfectly. However, after manually sliding through the images, the autoplay function stops working. When I try to use ionViewDidEnter(), it triggers an error... ...

Script for migrating MongoDB attributes to an array

I am in the process of creating a database migration, and the current structure is as follows: { "site" : { "name" : "siteName1" }, "subStages" : [ "subStage1", "s ...

What is the method for passing an element object instead of an id in JSXGraph?

I'm attempting to modify var brd2 = JXG.JSXGraph.initBoard('box', {boundingbox: [-8.75, 2.5, 8.75, -2.5]}); to read as var brd2 = JXG.JSXGraph.initBoard(this.$('#box'), {boundingbox: [-8.75, 2.5, 8.75, -2.5]}); Due to the creat ...

appearing like a straightforward process of creating strings in JavaScript

Originally, I thought this task would be easy, but it ended up taking me the entire morning! var insert = '<div class="main_content_half_panel_circle" id="circle_' + c + '"></div><script type="text/javascript">$("#circle_& ...

The Ajax data was not displayed in the console log, instead an error message was returned stating "http://localhost/IFICSV3/public/sla/sla/getbranch/180 not found"

I am attempting to make a dropdown option dependent on another using ajax. I want to view the data in the console to see if it is successful or not. I expect the data to be displayed in the console log, but instead, an error is being given. http://local ...

An introduction to utilizing .keypress() in jquery

I'm exploring the use of .keypress() to allow users to press enter and trigger a button click on my modal (which closes the modal). When I initially code it as: $(document).keypress(function () { console.log('keypress'); }); it works, but ...