[].concat.apply([], arrayOfArrays)
This is how I concat multiple arrays into one (they just hold numbers).
Unfortunately, when the number of arrays is too big, I get the Maximum stack depth exceeded. How to concat more arrays than VM can push on stack?
function test (msg,f) {
console.time(msg)
f()
console.timeEnd(msg)
}
function conc (a) {
return a.concat.apply([], a)
}
function push (a) {
var R = []
for(var i = 0; i < a.length; i++){
for(var j = 0; j < a[i].length; j++){
R .push (a[i][j])
}
}
return R
}
function conc2 (a) {
var R = []
for(var i = 0; i < a.length; i++)R.push.apply(R, a[i])
return R
}
L = []
for (var i = 0; i< 10000; i++) {
var S = []
for (var j = 0; j < 70; j++) S .push (Math.round (Math.random() * 500))
L.push(S)
}
//L = [[1,2], [3,4], [5,6], [7,8], [9,0]]
var A, B, C
test('concat', function (a,b,c) {
A = conc(L)
})
test('push', function (a,b,c) {
B = push(L)
})
test('concat2', function (a,b,c) {
C = conc2(L)
})
if (A.length < 200) console.log( JSON.stringify(A), JSON.stringify(B), JSON.stringify(C))
console.log( A.length, B.length, C.length)
Results are concat.apply:20ms, push:80ms, concat loop: 60 ms
apply
is so much faster! But it is limited to stack size. How to overcome the stack limit retaining performance?