mirror of
https://github.com/PR0M3TH3AN/bitvid.git
synced 2026-10-28 16:32:28 +00:00
Refactor `js/storage/dmDb.js` to use a singleton connection pattern for IndexedDB. Previously, the database was opened and closed for every single operation, leading to significant overhead. Changes: - Introduced `dbInstance` and `dbPromise` to cache the database connection. - Refactored `openDmDb` to reuse the existing connection or pending promise. - Added `onversionchange` handler to safely close the connection if an upgrade is requested. - Removed all manual `db.close()` calls from exported functions. - Added a benchmark script in `tests/benchmark-dm-db.mjs` to verify the improvement. Co-authored-by: PR0M3TH3AN <[email protected]>
45 lines
1.1 KiB
JavaScript
45 lines
1.1 KiB
JavaScript
import { writeMessages } from "../js/storage/dmDb.js";
|
|
import { indexedDB, IDBKeyRange } from "fake-indexeddb";
|
|
|
|
if (!globalThis.indexedDB) {
|
|
globalThis.indexedDB = indexedDB;
|
|
globalThis.IDBKeyRange = IDBKeyRange;
|
|
}
|
|
|
|
const ITERATIONS = 500;
|
|
|
|
async function benchmark() {
|
|
console.log(`Starting benchmark with ${ITERATIONS} iterations...`);
|
|
|
|
// Warm up
|
|
await writeMessages({
|
|
id: `warmup`,
|
|
conversationId: "bench-conv",
|
|
senderPubkey: "sender",
|
|
receiverPubkey: "receiver",
|
|
createdAt: Date.now(),
|
|
kind: 4,
|
|
content: "Warmup",
|
|
});
|
|
|
|
const start = performance.now();
|
|
|
|
for (let i = 0; i < ITERATIONS; i++) {
|
|
await writeMessages({
|
|
id: `msg-${i}`,
|
|
conversationId: "bench-conv",
|
|
senderPubkey: "sender",
|
|
receiverPubkey: "receiver",
|
|
createdAt: Date.now(),
|
|
kind: 4,
|
|
content: "Bench",
|
|
});
|
|
}
|
|
|
|
const end = performance.now();
|
|
console.log(`Total time for ${ITERATIONS} writes: ${(end - start).toFixed(2)}ms`);
|
|
console.log(`Average time per write: ${((end - start) / ITERATIONS).toFixed(2)}ms`);
|
|
}
|
|
|
|
benchmark().catch(console.error);
|