Performance: Derived stores
MEDIUM IMPACT
Derived stores affect how reactive data updates propagate and how often components re-render, impacting interaction responsiveness and rendering speed.
import { derived, writable } from 'svelte/store'; const storeA = writable(0); const storeB = writable(0); let timeout; const derivedStore = derived([storeA, storeB], ([$storeA, $storeB], set) => { // debounce or throttle expensive calculation if (timeout) clearTimeout(timeout); timeout = setTimeout(() => { let result = 0; for (let i = 0; i < 100000; i++) { result += $storeA * $storeB * i; } set(result); }, 50); return () => { if (timeout) { clearTimeout(timeout); timeout = null; } }; });
import { derived, writable } from 'svelte/store'; const storeA = writable(0); const storeB = writable(0); const derivedStore = derived([storeA, storeB], ([$storeA, $storeB]) => { // expensive calculation on every change let result = 0; for (let i = 0; i < 100000; i++) { result += $storeA * $storeB * i; } return result; });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Derived store with expensive calculation on every update | Minimal DOM changes | Triggers multiple reflows if UI updates | High paint cost due to slow JS | [X] Bad |
| Derived store with debounced expensive calculation | Minimal DOM changes | Single reflow per batch update | Lower paint cost due to less frequent JS work | [OK] Good |