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:
2 years ago
User agent:
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.61 Safari/537.36
Test name
Executions per second
native flat
405369.7 Ops/sec
flatPush
196251.7 Ops/sec
flatConcat
216556.4 Ops/sec
flatSpread
259593.6 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