-3

What is the fastest way to copy an array?

I decided to make a game, but I feel that Array.filter is too slow, so I created a method:

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

if without Array.from, this method takes only 130 - 295ms to remove 99999999 elements, because it just put element to remove at end of list, and slice out. Even filter takes 670 - 1330 ms to remove.

but when I test Array.from:

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

Why is Array.from so slow? It's 10 times slower than 'removeIf', and slower than Array.filter. Are there any faster way to copy list?

Cflowe Visit
  • 331
  • 1
  • 4
  • 12

1 Answers1

-3

Being completely honest, JS is not a good programming language for game development, and if you have an array that contains that many elements that you need to manipulate in less than 300ish ms then you're probably doing something wrong. However,

You could make it yourself, make a loop that goes through each element and pushes it to a different array. Quick example:

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

all that does is simply loop through each element, push it to the new array until done

or you could just do:

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

both of those would work, I'm unsure how fast they would be however, But it's the fastest method I could think of. Hopefully this helps :)

Umbel_
  • 36
  • 4
  • 1
    The first is a shallow copy without memory preallocation and the second isn't a copy of the array. – jabaa May 27 '22 at 18:23