diff --git a/benchmarks/profile_cache_storage_bench.js b/benchmarks/profile_cache_storage_bench.js new file mode 100644 index 00000000..feffb2a1 --- /dev/null +++ b/benchmarks/profile_cache_storage_bench.js @@ -0,0 +1,66 @@ +import { profileCache } from "../js/state/profileCache.js"; + +// Polyfill localStorage +const store = new Map(); +global.localStorage = { + getItem: (key) => store.get(key) || null, + setItem: (key, value) => store.set(key, value), + removeItem: (key) => store.delete(key), + clear: () => store.clear(), +}; + +// Polyfill requestIdleCallback +global.requestIdleCallback = (cb) => setTimeout(() => { + cb({ + timeRemaining: () => 50, + didTimeout: false + }); +}, 0); + +// Polyfill window (might be needed by logger or others) +if (typeof window === 'undefined') { + global.window = global; +} + +function generateLargeData() { + const data = []; + // Generate roughly 2MB of JSON data + for (let i = 0; i < 20000; i++) { + data.push({ id: i, content: "x".repeat(100) }); + } + return data; +} + +async function runBenchmark() { + const pubkey = "0".repeat(64); + const section = "watchHistory"; + const data = generateLargeData(); + + // Set active profile to ensure logic runs + profileCache.setActiveProfile(pubkey); + + console.log("Benchmarking setProfileData with large payload..."); + + // Warmup + profileCache.setProfileData(pubkey, section, [{id: 1}]); + + const start = performance.now(); + // We call it multiple times to amplify the effect, but a single call with 2MB is enough to show blocking + profileCache.setProfileData(pubkey, section, data); + const end = performance.now(); + + console.log(`Execution time (Synchronous part): ${(end - start).toFixed(4)} ms`); + + // Wait for idle callback + await new Promise(resolve => setTimeout(resolve, 50)); + + // Verify data is "stored" + const stored = localStorage.getItem(profileCache.getStorageKey(pubkey, section)); + if (stored) { + console.log("Data successfully stored in localStorage (length: " + stored.length + ")"); + } else { + console.log("Data NOT found in localStorage"); + } +} + +runBenchmark(); diff --git a/js/state/profileCache.js b/js/state/profileCache.js index 4e0bc561..14317b8b 100644 --- a/js/state/profileCache.js +++ b/js/state/profileCache.js @@ -16,6 +16,15 @@ const SECTION_TO_NOTE_TYPE = { "profile": NOTE_TYPES.PROFILE_METADATA, }; +// Helper to defer non-critical work to idle periods +function runIdle(callback) { + if (typeof requestIdleCallback !== "undefined") { + requestIdleCallback(callback); + } else { + setTimeout(callback, 1); + } +} + function sanitizeProfileString(value) { if (typeof value !== "string") { return ""; @@ -316,17 +325,19 @@ class ProfileCache { const storageKey = this.getStorageKey(pubkey, section); const tier = this.getStorageTier(section); - // Save to storage + // Save to storage (Optimized: defer blocking I/O) if (tier === STORAGE_TIERS.LOCAL_STORAGE && typeof localStorage !== "undefined") { - try { - if (data === null || data === undefined) { - localStorage.removeItem(storageKey); - } else { - localStorage.setItem(storageKey, JSON.stringify(data)); + runIdle(() => { + try { + if (data === null || data === undefined) { + localStorage.removeItem(storageKey); + } else { + localStorage.setItem(storageKey, JSON.stringify(data)); + } + } catch (error) { + userLogger.warn(`[ProfileCache] Failed to save ${section} for ${pubkey}`, error); } - } catch (error) { - userLogger.warn(`[ProfileCache] Failed to save ${section} for ${pubkey}`, error); - } + }); } // Update memory cache diff --git a/tests/profile-cache.test.mjs b/tests/profile-cache.test.mjs index 527ab7a4..fcd54338 100644 --- a/tests/profile-cache.test.mjs +++ b/tests/profile-cache.test.mjs @@ -79,7 +79,7 @@ test("ProfileCache: resolveAddressKey", (t) => { assert.equal(keyUnknown, `bitvid:profile:${pubkey}:unknownSection:v1`); }); -test("ProfileCache: set and get (memory and persistence)", (t) => { +test("ProfileCache: set and get (memory and persistence)", async (t) => { const pubkey = "c".repeat(64); profileCache.setActiveProfile(pubkey); @@ -98,6 +98,10 @@ test("ProfileCache: set and get (memory and persistence)", (t) => { // Check persistence const storageKey = profileCache.getStorageKey(pubkey, section); + + // Wait for async write (runIdle/setTimeout) + await new Promise((resolve) => setTimeout(resolve, 20)); + const storedRaw = localStorage.getItem(storageKey); assert.ok(storedRaw); assert.deepEqual(JSON.parse(storedRaw), data); @@ -110,7 +114,7 @@ test("ProfileCache: set and get (memory and persistence)", (t) => { assert.deepEqual(reloaded, data); }); -test("ProfileCache: setProfile normalization and storage", (t) => { +test("ProfileCache: setProfile normalization and storage", async (t) => { const pubkey = "d".repeat(64); const profileInput = { name: " Test User ", @@ -131,6 +135,10 @@ test("ProfileCache: setProfile normalization and storage", (t) => { // Verify persistence const storageKey = profileCache.getStorageKey(pubkey, "profile"); + + // Wait for async write (runIdle/setTimeout) + await new Promise((resolve) => setTimeout(resolve, 20)); + const stored = JSON.parse(localStorage.getItem(storageKey)); assert.deepEqual(stored.profile, entry.profile); });