Skip to content

Instantly share code, notes, and snippets.

@KelWill
Created March 6, 2022 16:07
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/132bdf052081b346cd37eb53880a942b to your computer and use it in GitHub Desktop.
Save KelWill/132bdf052081b346cd37eb53880a942b to your computer and use it in GitHub Desktop.
const Benchmark = require("benchmark");
const { ObjectId } = require("bson");
const _ = require("lodash");
const size = 100;
let array = new Array(size).fill(0).map(() => new ObjectId().toHexString());
const keyedDocs = _.keyBy(array);
const set = new Set(array);
const keysToGet = _.shuffle(array);
const suite = new Benchmark.Suite();
suite
.add("object access", function () {
let magic = true;
for (const key of keysToGet) {
magic = !!keyedDocs[key] || magic;
}
})
.add("set", function () {
let magic = true;
for (const key of keysToGet) {
magic = set.has(key) || magic;
}
})
.add("array", function () {
let magic = true;
for (const key of keysToGet) {
magic = array.includes(key) || magic;
}
})
.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