ReviewOS

stacks/stx

reactivity: `watch()` with a function source polls at 16ms with deep `JSON.stringify` comparison — CPU drain at scale

#1713
Closed glennmichael123 opened this 23 days ago · 0 comments
23 days ago

TL;DR

packages/stx/src/reactivity.ts:451-458 implements watch(source, callback, options) so that when source is a getter function (vs a ref/signal), it kicks off a setInterval(check, 16). Combined with options.deep (lines 422-430), each tick runs JSON.stringify(newValue) !== JSON.stringify(oldValue) then JSON.parse(JSON.stringify(newValue)) to clone the previous value. For a moderately deep object this is O(n) per tick at 60fps.

Why this is bad

  • Wakes the event loop continuously, even when nothing in the page is changing. Browsers can't idle the tab.
  • JSON-based comparison misses several update kinds: doesn't fire on +0 vs -0, on NaN → NaN, drops undefined properties, drops functions, loses Map/Set membership. So you pay the cost AND can miss real updates.
  • JSON-based clone breaks circular refs, Date, RegExp, typed arrays, Map, Set, class instances. Anything more structured than POJO + primitives is silently mishandled.
  • The 16ms cadence is hardcoded — there's no debounce, no requestIdleCallback, no opt-out.

This sits inside reactivity.ts's Vue-compat layer, so the typical user reaching it has just written:

watch(() => store.items.length, (n) => render(n))

…not realizing the function-source path is the slow branch. The signal-source path (watch(myCount, …)) is correct and reactive.

Proposed direction

The right model is to evaluate the source function inside the reactive graph (same way derived() does — track signal reads, re-fire on change). That eliminates polling entirely. The function-source watch() should desugar to:

function watch(source, callback, opts) {
  if (typeof source === 'function') {
    let prev = source()
    effect(() => {
      const next = source()    // tracks signal reads inside
      if (!sameValue(next, prev, opts.deep)) {
        callback(next, prev)
        prev = opts.deep ? structuredClone(next) : next
      }
    })
  } else {
    // ref / signal source — existing path
  }
}

That makes watch(() => store.items.length, …) behave the same as derived(() => store.items.length).subscribe(…) — no polling, fires only when an actually-tracked signal changes.

Other fixes worth bundling:

  • Replace JSON.stringify-based deep equality with Object.is for primitives + recursive structural comparison for objects (or use a vetted library).
  • Replace JSON.parse(JSON.stringify(...)) deep-clone with structuredClone (native, handles cyclic refs, Maps, Sets, dates).

Severity

Real perf hit at scale; mitigated by the fact that signal-source watch() (the common path) is fine. Function-source watch() is the common Vue-migration pattern, so the moment users adopt Vue-compat APIs they likely hit this.

Found during a deep-scan audit.

🤖 Filed via Claude Code

Sign in to comment on this issue.