From 243219b3771b5d5ee03d37ee6b6b008e88202d02 Mon Sep 17 00:00:00 2001 From: Meme11030 Date: Mon, 29 Jun 2026 15:59:25 +0000 Subject: [PATCH] perf: replace JSON.stringify with shallowEqual in synchronizationEngine Closes #733 - Add shallowEqual helper to compare per-key references/values - Replace JSON.stringify diff with shallowEqual per SYNC_KEYS entry - Eliminates full-state serialization on every Zustand update - BroadcastChannel only fires when persisted state actually changes --- src/store/synchronizationEngine.ts | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/src/store/synchronizationEngine.ts b/src/store/synchronizationEngine.ts index 50bba4fc..9ba7b329 100644 --- a/src/store/synchronizationEngine.ts +++ b/src/store/synchronizationEngine.ts @@ -2,6 +2,15 @@ import { useStore } from './stateManager'; const CHANNEL_NAME = 'teachlink_state_sync'; +/** Shallow equality: primitives compared by value, objects by reference-per-key. */ +function shallowEqual(a: any, b: any): boolean { + if (a === b) return true; + if (typeof a !== 'object' || a === null || typeof b !== 'object' || b === null) return false; + const keysA = Object.keys(a); + if (keysA.length !== Object.keys(b).length) return false; + return keysA.every(k => a[k] === b[k]); +} + const SYNC_KEYS = ['user', 'preferences', 'offlineMode', 'lastSynced'] as const; /** @@ -36,9 +45,7 @@ export class SynchronizationEngine { useStore.subscribe((state: any, prevState: any) => { if (this.isProcessingSync) return; - const hasChanged = SYNC_KEYS.some(key => - JSON.stringify((state as any)[key]) !== JSON.stringify((prevState as any)[key]) - ); + const hasChanged = SYNC_KEYS.some(key => !shallowEqual(state[key], prevState[key])); if (hasChanged) { this.broadcastState(state);