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?