Last active
December 1, 2023 22:16
-
-
Save KelWill/a4d001b3096c7be393ab06aeb0b7a70d to your computer and use it in GitHub Desktop.
benchmarking arr.find vs. dict lookup
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
const Benchmark = require("benchmark"); | |
const { ObjectId } = require("bson"); | |
const _ = require("lodash"); | |
const casual = require("casual") | |
const size = 1000; | |
let array = new Array(size).fill(0).map(() => new ObjectId().toHexString()); | |
const docs = array.map((_id) => ({ | |
_id, | |
firstName: casual.name, | |
lastName: casual.name, | |
email: casual.email, | |
})); | |
const keyedDocs = _.keyBy(docs, "_id") | |
const keysToGet = _.shuffle(array); | |
const suite = new Benchmark.Suite(); | |
function doNothing() { } | |
suite | |
.add("object access", function () { | |
let result = keysToGet.map((_id) => keyedDocs[_id]); | |
doNothing(result) | |
}) | |
.add("array", function () { | |
let result = [] | |
for (const key of keysToGet) { | |
result.push(docs.find((doc) => doc._id === key)); | |
} | |
doNothing(result) | |
}) | |
.on("cycle", (event) => { | |
console.log(`\t ${size}`, String(event.target)); | |
}) | |
.on("complete", function () { | |
console.log( | |
`Fastest for ${size} is ` + | |
this.filter("fastest").map("name") | |
); | |
console.log("\n\n"); | |
}) | |
.run({ async: false }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment