javascript - Concat more arrays than stack allows -
[].concat.apply([], arrayofarrays)
this how concat multiple arrays 1 (they hold numbers).
unfortunately, when number of arrays big, maximum stack depth exceeded. how concat more arrays 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 = 0; < 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 = 0; < a.length; i++)r.push.apply(r, a[i]) return r } l = [] (var = 0; i< 10000; i++) { var s = [] (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) { = 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 concat.apply:20ms, push:80ms, concat loop: 60 ms
apply
faster! limited stack size. how overcome stack limit retaining performance?
assuming basic structure of arrayofarrays
, this.
var arrayofarrays = [ [0, 1, 2], [3, 4, 5], [6, 7, 8] ], result1 = [].concat.apply([], arrayofarrays), result2 = arrayofarrays.reduce(function (acc, arr) { return acc.concat(arr); }, []); document.getelementbyid('out').textcontent = json.stringify(result1, null, 2) + '\n' +json.stringify(result2, null, 2);
<pre id="out"></pre>
Comments
Post a Comment