Skip to content

Instantly share code, notes, and snippets.

@netanel-haber
Last active October 4, 2022 10:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save netanel-haber/e8f99db2854fe6de5728f63558a225a1 to your computer and use it in GitHub Desktop.
Save netanel-haber/e8f99db2854fe6de5728f63558a225a1 to your computer and use it in GitHub Desktop.
// https://stackoverflow.com/questions/61411776/is-js-native-array-flat-slow-for-depth-1
// [--jsperf is down--] https://jsperf.com/flat-array-depth-1 - I added this jsperf benchmark after this gist was created and the SO question was asked.
let TenThouWideArray = Array(1000).fill().map(el => Array(10).fill(1));
let TenThouNarrowArray = Array(10).fill().map(el => Array(1000).fill(1));
let TenMilWideArray = Array(10000).fill().map(el => Array(1000).fill(1));
let TenMilNarrowArray = Array(100).fill().map(el => Array(100000).fill(1));
let benchmarks = { TenThouWideArray, TenThouNarrowArray, TenMilWideArray, TenMilNarrowArray };
let implementations = [
flattenPreAllocated,
flattenNotPreAllocated,
function nativeFlat(arr) { return Array.prototype.flat.call(arr) },
function spreadThenConcat(arr) { return [].concat(...arr) }
];
let result;
Object.keys(benchmarks).forEach(arrayName => {
console.log(`\n............${arrayName}............\n`)
implementations.forEach(impl => {
console.time(impl.name);
result = impl(benchmarks[arrayName]);
console.timeEnd(impl.name);
})
console.log(`\n............${arrayName}............\n`)
})
function flattenPreAllocated(arr) {
let numElementsUptoIndex = Array(arr.length);
numElementsUptoIndex[0] = 0;
for (let i = 1; i < arr.length; i++)
numElementsUptoIndex[i] = numElementsUptoIndex[i - 1] + arr[i - 1].length;
let flattened = new Array(numElementsUptoIndex[arr.length - 1] + arr[arr.length - 1].length);
let skip;
for (let i = 0; i < arr.length; i++) {
skip = numElementsUptoIndex[i];
for (let j = 0; j < arr[i].length; j++)
flattened[skip + j] = arr[i][j];
}
return flattened;
}
function flattenNotPreAllocated(arr) {
let flattened = [];
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[i].length; j++) {
flattened.push(arr[i][j])
}
}
return flattened;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment