Array concat vs spread operator vs push for array flat implementation
Compare the new ES6 spread operator with the traditional concat() method and push
Date tested:
3 years ago
User agent:
Mozilla/5.0 (Macintosh; Intel Mac OS X 11_2_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36
Test name
Executions per second
native flat
133663.3 Ops/sec
flatPush
130928.5 Ops/sec
flatConcat
113044.2 Ops/sec
flatSpread
139164.9 Ops/sec
Benchmark definition (click to collapse):
Script Preparation code:
var isArray = Array.isArray; var sourceArray = [1, [1, 2, [3, 4, [5, 6]]], 2, [3, 4, [1, 2, [3, [1, 2, [3, 4]], 4]], [5, 6, [1, 2, [3, 4, [5, 6]]], [7, 8, [9, 10]]]]]; function flatPush(arr, depth) { if (depth === undefined) { depth = 100; } else if (depth <= 0) { return arr; } var result = []; for (var len = arr.length, i = 0, val; i < len; ++i) { if (isArray((val = arr[i]))) { val = flatPush(val, depth - 1); for (var jen = val.length, j = 0; j < jen; ++j) { result.push(val[j]); } } else { result.push(val); } } return result; } function flatConcat(arr, depth) { if (depth === undefined) { depth = 100; } else if (depth <= 0) { return arr; } var result = []; for (var len = arr.length, i = 0, val; i < len; ++i) { if (isArray((val = arr[i]))) { result = result.concat(flatConcat(val, depth - 1)); } else { result.push(val); } } return result; } function flatSpread(arr, depth) { if (depth === undefined) { depth = 100; } else if (depth <= 0) { return arr; } var result = []; for (var len = arr.length, i = 0, val; i < len; ++i) { if (isArray((val = arr[i]))) { result.push(...flatSpread(val, depth - 1)); } else { result.push(val); } } return result; }
Tests:
native flat
return sourceArray.flat(100);
flatPush
return flatPush(sourceArray);
flatConcat
return flatConcat(sourceArray);
flatSpread
return flatSpread(sourceArray);
Open this result on MeasureThat.net