Skip to content

Instantly share code, notes, and snippets.

@DrMegavolt
Created March 18, 2023 02:48
Show Gist options
  • Select an option

  • Save DrMegavolt/813e5dfcc70b395dd562101a2ce11da0 to your computer and use it in GitHub Desktop.

Select an option

Save DrMegavolt/813e5dfcc70b395dd562101a2ce11da0 to your computer and use it in GitHub Desktop.
benchmark for uuid, cuid, ksuid, ulid, ObjectId in mongodb
const MongoClient = require("mongodb").MongoClient;
const ObjectID = require("mongodb").ObjectId;
const { v4: uuidv4 } = require("uuid");
const cuid = require("cuid");
const ulid = require("ulid").ulid;
const Snowflake = require("node-snowflake").Snowflake;
const KSUID = require("ksuid");
const uri = process.env.MONGO_CS || "mongodb://localhost:27017";
const dbName = "benchmark";
const numDocuments = 1000000;
const client = new MongoClient(uri, { useUnifiedTopology: true });
async function benchmark(collectionName, idGenerator) {
const collection = client.db(dbName).collection(collectionName);
const startTime = Date.now();
for (let i = 0; i < numDocuments; i++) {
await collection.insertOne({
_id: idGenerator(),
field: "example_data",
});
}
const endTime = Date.now();
console.log(
`Inserted ${numDocuments} documents in ${collectionName} in ${
(endTime - startTime) / 1000
}s`
);
}
(async function () {
try {
await client.connect();
await client.db(dbName).dropDatabase();
console.log("Starting benchmark...");
await benchmark("ksuids", () => KSUID.randomSync().string);
await benchmark("uuids", uuidv4);
await benchmark("cuids", cuid);
await benchmark("ulids", ulid);
await benchmark("objectids", () => new ObjectID());
} catch (error) {
console.error("Error during benchmark:", error);
} finally {
await client.close();
}
})();
{
"name": "ids-test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"cuid": "^3.0.0",
"ksuid": "^3.0.0",
"mongodb": "^5.1.0",
"node-snowflake": "^0.0.1",
"ulid": "^2.3.0",
"uuid": "^9.0.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment