perf: virtual-core rewrite for mount/measure-storm, plus iOS Safari handling and scroll restoration #1168
Mergedtannerlinsleymerged 43 commits into
main fromrefs/pull/1168/headmerged by tannerlinsley - benchmarks/README.md lines 31 to 45OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +25,21 @@25+26+Results land in `benchmarks/results/<timestamp>.json` (raw, every run) and27+`benchmarks/results/LATEST.md` (median table from the last run).28+29+## How it works30+31+```32+benchmarks/33+├── src/34+│ ├── main.tsx Reads ?lib=... &scenario=...35+│ ├── pages/ One file per library; all share the same harness36+│ ├── lib/37+│ │ ├── dataset.ts Deterministic item generator (LCG-seeded)38+│ │ └── harness.ts Installs window.bench.run() that every page uses39+│ └── scenarios/types.ts The fixed scenario list. Adding a row here40+│ surfaces it in every library and the runner.41+├── runner/run.mjs Playwright driver. Boots a server, runs each42+│ (lib × scenario × run), aggregates medians.43+├── results/ JSON snapshots + LATEST.md44+└── package.json45+```benchmarks/README.md line 162OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +142,21 @@142+143+## Bottom line144+145+**Small-to-medium variable-size lists** (the most common use case) —146+ TanStack is consistently the fastest to mount, tied on dynamic measurement,147+ competitive on memory.148+**Huge fixed-size lists (100k+ items)** — virtua wins decisively on mount149+ time and memory because its lazy prefix-sum cache only materializes the150+ visible window. TanStack's eager `measurementsCache` is the cost.151+**Scroll perf** — at the list sizes / workloads tested, all four152+ libraries sustain 60 fps with zero dropped frames.153+**Jump-to-index** — react-window leads, TanStack lands ~15 ms slower,154+ virtuoso 2× slower than the leader.155+156+## Notes on fairness157+158+Each page is implemented with the library's _recommended_ API. For example,159+ TanStack uses `useVirtualizer` + `measureElement`; virtua uses `VList` with160+ the `data`/`item` props; virtuoso uses `Virtuoso` with `fixedItemHeight`161+ when applicable; react-window uses `List` + `useDynamicRowHeight`.162+React 19 runs in production mode (no `<StrictMode>`).benchmarks/runner/run.mjs lines 81 to 105Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +83,21 @@83+ await page.goto(url, { waitUntil: 'domcontentloaded' })84+ // Wait until the harness reports ready (means React mounted and registered).85+ await page.waitForFunction(() => !!window.bench?.ready?.(), null, {86+ timeout: 15_000,87+ })88+ // Pull the scenario object back from the page so we run with the exact same89+ // shape the page is using.90+ const result = await page.evaluate(async (id) => {91+ const mod = await import('/src/scenarios/types.ts')92+ const scenario = mod.SCENARIOS.find((s) => s.id === id)93+ if (!scenario) throw new Error('unknown scenario: ' + id)94+ // Force GC where supported so memory readings aren't poisoned by previous run.95+ if ('gc' in globalThis) {96+ try {97+ globalThis.gc()98+ } catch {}99+ }100+ return await window.bench.run(scenario)101+ }, scenarioId)102+ return result103+}benchmarks/runner/run.mjs lines 92 to 94Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +73,21 @@73+ process.stderr.write(`[server] ${d.toString()}`),74+ )75+ child.stderr?.on('data', (d) =>76+ process.stderr.write(`[server-err] ${d.toString()}`),77+ )78+ return child79+}80+81+async function runScenario(page, lib, scenarioId) {82+ const url = `${BASE}/?lib=${lib}&scenario=${scenarioId}`83+ await page.goto(url, { waitUntil: 'domcontentloaded' })84+ // Wait until the harness reports ready (means React mounted and registered).85+ await page.waitForFunction(() => !!window.bench?.ready?.(), null, {86+ timeout: 15_000,87+ })88+ // Pull the scenario object back from the page so we run with the exact same89+ // shape the page is using.90+ const result = await page.evaluate(async (id) => {91+ const mod = await import('/src/scenarios/types.ts')92+ const scenario = mod.SCENARIOS.find((s) => s.id === id)93+ if (!scenario) throw new Error('unknown scenario: ' + id)benchmarks/runner/run.mjs lines 288 to 297Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +270,21 @@270+ scenario: { id: scenarioId },271+ metrics,272+ ranAt: new Date().toISOString(),273+ })274+ process.stderr.write(275+ `mount=${fmt(metrics.mountMs)}ms action=${fmt(metrics.actionMs)}ms`,276+ )277+ } catch (e) {278+ process.stderr.write(`ERROR: ${e.message}`)279+ results.push({280+ library: lib,281+ scenario: { id: scenarioId },282+ metrics: {283+ mountMs: NaN,284+ firstPaintMs: NaN,285+ actionMs: NaN,286+ scrollFps: null,287+ longFrames: null,288+ jankMs: null,289+ memoryBytes: null,290+ },benchmarks/src/lib/dataset.ts line 57OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +37,21 @@37+ 'victor',38+ 'whiskey',39+ 'x-ray',40+ 'yankee',41+ 'zulu',42+]43+44+// Simple LCG so the same seed yields the same sequence in any JS runtime.45+function lcg(seed: number) {46+ let s = seed >>> 047+ return () => {48+ s = (s * 1664525 + 1013904223) >>> 049+ return s / 0x10000000050+ }51+}52+53+export function makeDataset(54+ count: number,55+ dynamic: boolean,56+ wideVariance = false,57+): Item[] {benchmarks/src/pages/VirtuaPage.tsx lines 38 to 50Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +28,21 @@28+ const hostRef = useRef<HTMLDivElement>(null)29+ const measuredSet = useRef(new Set<number>())30+31+ useEffect(() => {32+ registerHarness({33+ getScrollContainer: () => hostRef.current,34+ scrollToIndex: (i, opts) =>35+ ref.current?.scrollToIndex(i, {36+ align: opts?.align ?? 'start',37+ }),38+ getTotalSize: () => {39+ const el = hostRef.current?.querySelector(40+ '[style*="height:"]',41+ ) as HTMLElement | null42+ // VList sets scrollSize implicitly; fall back to scrollHeight.43+ return (44+ (hostRef.current?.firstElementChild as HTMLElement | null)45+ ?.scrollHeight ??46+ hostRef.current?.scrollHeight ??47+ 048+ )benchmarks/src/scenarios/types.ts line 59OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +39,21 @@39+ jankMs: number | null40+ /** Heap snapshot after mount (Chromium only; null elsewhere). */41+ memoryBytes: number | null42+ /** Accuracy metric for jump-to-middle: |actual landing position - target| in pixels.43+ * Lower is better. Null for scenarios that don't measure accuracy. */44+ landingErrorPx: number | null45+}46+47+export interface ScenarioResult {48+ library: LibraryName49+ scenario: ScenarioInput50+ metrics: ScenarioMetrics51+ /** ISO timestamp the scenario ran. */52+ ranAt: string53+ /** Notes from the page (e.g. opt-outs, library-specific caveats). */54+ notes?: string55+}56+57+// The fixed scenarios all libraries run. Adding scenarios here surfaces them58+// in the runner without further plumbing.59+export const SCENARIOS: ScenarioInput[] = [packages/virtual-core/src/index.ts lines 708 to 716Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -590,0 +688,21 @@688+ // past the post-touchend grace window. Called from the scroll callback689+ // and the touchend grace-timer.690+ private _flushIosDeferredIfReady = () => {691+ if (this._iosDeferredAdjustment === 0) return692+ if (this.isScrolling) return693+ if (this._iosTouching) return694+ if (this._iosJustTouchEnded) return695+ // Phase 2b: Safari elastic-overscroll (rubber-band) lets scrollTop go696+ // negative or beyond scrollHeight - clientHeight. Writing scrollTop697+ // while in that zone snaps the page back to the clamped value at the698+ // end of the bounce, often discarding the user's intent. Skip the699+ // flush; the next in-bounds scroll event will retry.700+ const cur = this.getScrollOffset()701+ const max = this.getMaxScrollOffset()702+ if (cur < 0 || cur > max) return703+ const delta = this._iosDeferredAdjustment704+ this._iosDeferredAdjustment = 0705+ this._scrollToOffset(cur, {706+ adjustments: delta,707+ behavior: undefined,708+ })@@ -1316,10 +1609,14 @@13161609 behavior: ScrollBehavior | undefined13171610 },13181611 ) => {1612+ // Record the intended logical scroll target so the next scroll event1613+ // can reconcile against subpixel rounding by the browser.1614+ this._intendedScrollOffset = offset + (adjustments ?? 0)13191615 this.options.scrollToFn(offset, { behavior, adjustments }, this)13201616 }1321161713221618 measure = () => {1323- this.itemSizeCache = new Map()1324- this.laneAssignments = new Map() // Clear lane cache for full re-layout1619+ this.itemSizeCache.clear()1620+ this.laneAssignments.clear() // Clear lane cache for full re-layout1621+ this.itemSizeCacheVersion++13251622 this.notify(false)packages/virtual-core/tests/index.test.ts lines 1323 to 1337OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -504,0 +1317,21 @@1317+ // Item at offset 500 should be index 16 (500/30 = 16.67)1318+ expect(found?.index).toBe(16)1319+ expect(found?.start).toBe(480)1320+ expect(found?.end).toBe(510)1321+})1322+1323+test('lazy fast path: large list (1M items) does not allocate per-item objects upfront', () => {1324+ const start = performance.now()1325+ const v = new Virtualizer({1326+ count: 1_000_000,1327+ estimateSize: () => 30,1328+ getScrollElement: () => null,1329+ scrollToFn: vi.fn(),1330+ observeElementRect: vi.fn(),1331+ observeElementOffset: vi.fn(),1332+ })1333+ v['getMeasurements']()1334+ const elapsed = performance.now() - start1335+ // Should be sub-50ms even at 1M items (typed array fill + proxy alloc only)1336+ expect(elapsed).toBeLessThan(50)1337+})
SeanCassiere reviewed
@@ -0,0 +1 @@1+{"sessionId":"e402bf71-ca74-4aa5-856c-da0c2053caab","pid":78596,"procStart":"Sat May 16 20:13:35 2026","acquiredAt":1779000018499}piecyk approved these changes
@@ -1,3 +1,17 @@1+import { createLazyMeasurementsView } from './lazy-measurements'12 import { approxEqual, debounce, memo, notUndefined } from './utils'233-export * from './utils'4+// Browser-aware iOS detection. Programmatic `scrollTo`/`scrollTop` writes5+// during a momentum-scroll cancel the momentum on iOS WebKit, so we defer6+// scroll-position adjustments triggered by mid-scroll resizes until the7+// scroll settles. SSR-safe (returns false when navigator is unavailable).8+let _isIOSResult: boolean | undefined9+const isIOSWebKit = (): boolean => {10+ if (_isIOSResult !== undefined) return _isIOSResult11+ if (typeof navigator === 'undefined') return (_isIOSResult = false)12+ if (/iP(hone|od|ad)/.test(navigator.userAgent)) return (_isIOSResult = true)13+ // iPadOS 13+ reports as MacIntel; touch-points distinguishes it from desktop.14+ const mtp = (navigator as Navigator & { maxTouchPoints?: number })15+ .maxTouchPoints16+ return (_isIOSResult =17+ navigator.platform === 'MacIntel' && mtp !== undefined && mtp > 0)tannerlinsley merged this99355ad
tannerlinsley closed this
Sign in to join this conversation.
No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
e4427df1-ff77-4d56-9e98-ff5a8a116f34📥 Commits
Reviewing files that changed from the base of the PR and between ab9c00fe811d0cc00b000b89429b593f5080ae2d and 186b3bd60dd1f050270ca62ecfc7d968f79e3a11.
📒 Files selected for processing (2)
.changeset/fix-core-elementscache-stale-index.mdpackages/virtual-core/src/index.ts✅ Files skipped from review due to trivial changes (1)
📝 Walkthrough
Virtual core + benchmarks: complete change stack All changes in this PR: changesets, docs, benchmarks, virtual-core core refactors (typed-array fast path, iOS scroll handling, reconciliation, takeSnapshot), tests, and small react-virtual tweak.Single cohesive cohort covering the full set of related changes in the PR: release notes, benchmark workspace, core library implementation and optimizations, tests, and docs.
Contains every changed rangeId for the PR. Reviewers should inspect in semantic order: release/docs, benchmark infra, core implementation (utils, observers, flat measurements, fast paths, resize/scroll handling, snapshot), tests/benches.
range_437920e6a8c0 range_5643668018b9 range_c9a37415b5ea range_384c7e8bef1a range_210458182c88 range_8762c85a993a range_ca54fd3e3f94 range_fa8b74866f17 range_5b22db72b1e4 range_c7a94c20fe62 range_64102c1564cb range_42e54b5fe3b3 range_a22116d5b35d range_36b56d720385 range_0d023021201b range_6fbe0c37f866 range_0e74dbf43d41 range_a4cac3aff091 range_7e0e5d5377aa range_23a922dec5b2 range_22cc6fbe9438 range_e56fb78142de range_a1ad641aabd7 range_35d4101fd7ba range_7e1df3bdf167 range_5d5ceb82beab range_5b0245d47bff range_cdfd770b85f6 range_2c7899417251 range_d80dda1138f5 range_303baa9d37ba range_c8d0c8cc76c0 range_38ca836ce913 range_117b77b2a752 range_6bb647ac17b5 range_706867e6afee range_2b5379b9a5c4 range_96e215b0c73d range_5e4c7f2de1d9 range_0592d69c30e5 range_65581c125258 range_0f3a73e835d1 range_8dc5734c92ec range_0f4fb3489b76 range_579e1360e569 range_dcf586b99541 range_b1595d3902c6 range_c6ec57ed6a61 range_de78d6e3d1a4 range_0dbdf14ead32 range_5eca6e8056e5 range_0332ea734df0 range_a5e508142235 range_d55b7eab19dc range_afe8b94fc289 range_0746f3768ce8 range_1a3d5b3401ae range_638b5348b44e range_4e01fa951029 range_c452511863a0 range_c5287f6ea393 range_4e36dda31725 range_89d4d627707b range_e57587c42b9f range_347039695a9a range_8ffb51658e47 range_66118a405c41 range_710db081e225 range_f3820211525c range_867084521367 range_99b97d20ce16 range_1d2dabdc3a1d range_30a6f1a9d664 range_cf8d0e331932 range_c738b5f32166 range_f3bd27945891 range_4ed743629973 range_0fc119685f77 range_06ac0b8d208f range_9d4728877e7c range_da3a4fdda6ef range_6bbcadf218a7 range_00cb3b4feb9a range_1b36257e7689 range_ac104a6223c1 range_813517c9c8c1 range_bb9e0bf9cc0e range_2cb1bee0f8c3 range_0557e1632198 range_a9f793d41229 range_debf8d0a4b8d range_bed0a0717d80 range_43d6f964c324 range_e2ff55ee097d range_b38443b376d4 range_f1c15d07a1de range_c3b6b25c5cf1 range_c8cb3d26ef6b range_170b8f965357 range_0ab60610b16e range_5dd0c8701361 range_ce269f356483 range_2e7af262b199 range_c7dfb10adc6d range_e405239f658e range_335cfc4dac49 range_f0f3411e5b75 range_6fdf894f31d7 range_c17818be1785 range_3705762df72c range_c8449d3d9989 range_32044720a21a range_e7072369f60c range_22708fc8ccbc🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)#
✅ Passed checks (4 passed)
✨ Finishing Touches
📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment `@coderabbitai help` to get the list of available commands and usage tips.