Last active
November 10, 2023 09:21
-
-
Save davestewart/5ec71b0b21b3b200dc0741d1cfb2c5e3 to your computer and use it in GitHub Desktop.
.filter().map() pedantry!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let values = [] | |
let scores = [] | |
function prepare (length = 10_000_000) { | |
values = (new Array(length)).fill(1).map((e, i) => i) | |
} | |
function forIn () { | |
const output = [] | |
for (let i = 0; i < values.length; i++) { | |
if (values[i] % 2) { | |
output.push({ value: values[i] }) | |
} | |
} | |
return output | |
} | |
function forOf () { | |
const output = [] | |
for (const value of values) { | |
if (value % 2) { | |
output.push({ value }) | |
} | |
} | |
return output | |
} | |
function filterMap () { | |
return values | |
.filter(value => value % 2) | |
.map(value => ({ value })) | |
} | |
function mapFilter () { | |
return values | |
.map(value => ({ value })) | |
.filter(el => el.value % 2) | |
} | |
function reducePush () { | |
return values | |
.reduce((output, value) => { | |
if (value % 2) { | |
output.push({ value }) | |
} | |
return output | |
}, []) | |
} | |
function reduceConcat () { | |
return values | |
.reduce((output, value) => { | |
return value % 2 | |
? output.concat({ value }) | |
: output | |
}, []) | |
} | |
function reduceSpread () { | |
return values | |
.reduce((output, value) => { | |
return value % 2 | |
? [...output, { value }] | |
: output | |
}, []) | |
} | |
function test (fn) { | |
const d = Date.now() | |
fn() | |
const name = fn.name | |
const time = Date.now() - d | |
scores.push({ name, time }) | |
console.log(name, time) | |
} | |
function results () { | |
const results = scores | |
.filter(result => result.name !== 'prepare') | |
.sort((a, b) => { | |
a = a.time | |
b = b.time | |
return a < b | |
? -1 | |
: a > b | |
? 1 | |
: 0 | |
}) | |
console.table(results) | |
} | |
// build data | |
test(prepare) | |
// tests | |
test(forIn) | |
test(forOf) | |
test(filterMap) | |
test(mapFilter) | |
test(reducePush) | |
// test(reduceConcat) // 1500 x slower than reduce push | |
// test(reduceSpread) // 10500 x slower than reduce push | |
// results | |
results() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment