Skip to content

Instantly share code, notes, and snippets.

@KelWill
Last active December 1, 2023 22:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KelWill/a4d001b3096c7be393ab06aeb0b7a70d to your computer and use it in GitHub Desktop.
Save KelWill/a4d001b3096c7be393ab06aeb0b7a70d to your computer and use it in GitHub Desktop.
benchmarking arr.find vs. dict lookup
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