From 14964123ac7ea1fd30c1717d46c7f7454d121429 Mon Sep 17 00:00:00 2001 From: PLASMA-FR <173463847+PLASMA-FR@users.noreply.github.com> Date: Sun, 6 Dec 2026 09:50:22 +0000 Subject: [PATCH] fix(react-devtools): count render work across sibling subtrees --- .../src/index-react-profile.test.ts | 28 +++++++++- .../react-profile-analysis.test.ts | 56 ++++++++++++++----- .../react-devtools/react-profile-analysis.ts | 47 ++++++++-------- .../react-profile-format.test.ts | 7 ++- .../react-devtools/react-profile-format.ts | 10 ++-- .../react-devtools/react-profile-renders.ts | 8 +++ src/commands/schema/cli-help.ts | 1 + website/docs/docs/debugging-profiling.md | 2 + 8 files changed, 114 insertions(+), 45 deletions(-) diff --git a/packages/react-native/src/index-react-profile.test.ts b/packages/react-native/src/index-react-profile.test.ts index 60f22a18f13..a25391742ba 100644 --- a/packages/react-native/src/index-react-profile.test.ts +++ b/packages/react-native/src/index-react-profile.test.ts @@ -72,14 +72,38 @@ test('profile start, an interaction, and profile stop print a compact diagnosis ); assert.match( (await run('commit', '--limit', '1')).text, - /^Commits \(1 slowest of 3, --limit 3 for all\):\n {2}#0 \+0\.0s 40ms 13 rendered <- List$/, + /^Commits \(1 slowest of 3, --limit 3 for all\):\n {2}#0 \+0\.0s 37ms 13 rendered <- List$/, ); assert.match( (await run('commit', '#1')).text, - /^#1 \+0\.2s 40ms 13 rendered <- List\n {2}Row \[memo\] x12 self 36ms props/, + /^#1 \+0\.2s 37ms 13 rendered <- List\n {2}Row \[memo\] x12 self 36ms props/, ); }); +test('profile stop and saved commit agree on work from three independently updated siblings', async () => { + const { app, run } = harness(); + await run('start'); + // Timings captured from one synchronous update with React DOM 19.2.0 and DevTools 7.0.1. + app.renderer.commit(encodeOperations({ add: [3, 4, 5].map((id) => ({ id, name: 'Child' })) }), { + timestamp: 30.09, + duration: 9.484, + fibers: [ + [3, 9.484, 9.423], + [4, 9.199, 9.117], + [5, 9.13, 9.106], + ], + }); + const workMs = 9.423 + 9.117 + 9.106; + const stopped = await run('stop'); + assert.partialDeepStrictEqual(stopped.data, { + renderMs: workMs, + slowCommitCount: 1, + worstCommit: { index: 0, durationMs: 9.484, workMs }, + }); + const saved = await run('commit', '0'); + assert.partialDeepStrictEqual(saved.data, { durationMs: 9.484, workMs }); +}); + test('profile stop returns the findings and where the profile was saved', async () => { const { app, run, stateDir } = harness(); await run('start'); diff --git a/packages/react-native/src/react-devtools/react-profile-analysis.test.ts b/packages/react-native/src/react-devtools/react-profile-analysis.test.ts index 49c68ed4ed6..519d50013d0 100644 --- a/packages/react-native/src/react-devtools/react-profile-analysis.test.ts +++ b/packages/react-native/src/react-devtools/react-profile-analysis.test.ts @@ -197,7 +197,7 @@ test('a follow-up commit counts once per component however many of its instances ); assert.match( chain?.evidence ?? '', - /^3 follow-up commits it triggered right after rendering, likely state set in an effect \(30ms\)$/, + /^3 follow-up commits it triggered right after rendering, likely state set in an effect \(27ms\)$/, ); }); @@ -254,7 +254,7 @@ test('many commits from one updater in a short span are a render storm', () => { ); const [finding] = analyzeReactProfile(raw).findings; assert.equal(finding?.kind, 'render-storm'); - assert.match(finding?.evidence ?? '', /^40 commits in 0\.6s \(63\/s, 20ms rendering\)$/); + assert.match(finding?.evidence ?? '', /^40 commits in 0\.6s \(63\/s, 16ms rendering\)$/); }); test('mounting hundreds of one component in a commit is an eager list, reported once per component', () => { @@ -272,14 +272,14 @@ test('a component mounted eagerly in several commits is one finding costed acros const tiles = repeat(250, (i) => 10 + i); const elements: Record = { 1: ['Catalog'] }; for (const id of tiles) elements[id] = ['Tile', FUNCTION, 1]; - const mount = (at: number, duration: number): [number, number, number[], Render[]] => [ + const mount = (at: number, tileMs: number): [number, number, number[], Render[]] => [ at, - duration, + 5 + tiles.length * tileMs, [1], - [[1, 5, [0, null, [0], null]], ...tiles.map((id): Render => [id, 1, 1, duration / 300])], + [[1, 5, [0, null, [0], null]], ...tiles.map((id): Render => [id, tileMs, 1])], ]; const [finding, ...rest] = analyzeReactProfile( - rawProfile(elements, [mount(0, 300), mount(1_000, 600)]), + rawProfile(elements, [mount(0, 1), mount(1_000, 2)]), ).findings; assert.equal(finding?.kind, 'eager-mount'); @@ -287,7 +287,7 @@ test('a component mounted eagerly in several commits is one finding costed acros assert.equal(Math.round(finding!.costMs), 750); assert.match( finding!.evidence, - /^250 instances mounted at once in commit #1, 500ms of its 600ms/, + /^250 instances mounted at once in commit #1, 500ms of its 505ms/, ); assert.match(finding!.evidence, /; 2 such commits, 750ms in all$/); }); @@ -422,7 +422,7 @@ test('time inside a subtree a finding accounts for is not counted twice', () => ); assert.match( findings.find((finding) => finding.kind === 'slow-commit')?.evidence ?? '', - /^commit #12 took 100ms/, + /^commit #12 took 97ms/, 'Panel accounts for 40ms including Box, which leaves most of the commit unexplained', ); }); @@ -486,7 +486,7 @@ test('a slow commit nobody explains is reported with its heaviest components', ( assert.equal(finding?.component, 'Login'); assert.equal( finding?.evidence, - 'commit #0 took 90ms rendering 3 components (3 mounted) after Login updated; most time in Text 30ms, Login 12ms, Form 8.0ms', + 'commit #0 took 50ms rendering 3 components (3 mounted) after Login updated; most time in Text 30ms, Login 12ms, Form 8.0ms', ); }); @@ -536,13 +536,43 @@ test('cheap patterns stay below the noise floor', () => { test('the summary counts commits over the frame budget and names the worst', () => { const raw = rawProfile({ 1: ['A'] }, [ - [0, 10, [1], [[1, 1]]], - [100, 40, [1], [[1, 1]]], - [200, 20, [1], [[1, 1]]], + [0, 10, [1], [[1, 10]]], + [100, 40, [1], [[1, 40]]], + [200, 20, [1], [[1, 20]]], ]); const analysis = analyzeReactProfile(raw); assert.equal(analysis.slowCommitCount, 2); - assert.deepEqual(analysis.worstCommit, { index: 1, durationMs: 40 }); + assert.deepEqual(analysis.worstCommit, { index: 1, durationMs: 40, workMs: 40 }); assert.equal(analysis.renderMs, 70); assert.equal(analysis.wallMs, 5_000); }); + +test('independent subtrees contribute their self time to the commit, including unnamed fibers', () => { + const raw = rawProfile( + { 1: ['Single'], 2: ['Panel'], 3: ['Child', FUNCTION, 2, 2], 4: ['Sibling'], 5: ['Footer'] }, + [ + [0, 25, [], [[1, 25]]], + [ + 100, + 14, + [], + [ + [2, 5, 'parent', 14], + [3, 9], + [4, 14], + [5, 14], + [6, 14], + ], + ], + ], + ); + const analysis = analyzeReactProfile(raw); + assert.equal(analysis.renderMs, 81); + assert.equal(analysis.slowCommitCount, 2); + assert.deepEqual(analysis.worstCommit, { index: 1, durationMs: 14, workMs: 56 }); + assert.equal(analysis.commits[1]?.durationMs, 14); + assert.equal(analysis.commits[1]?.workMs, 56); + const finding = analysis.findings.find((entry) => entry.kind === 'slow-commit'); + assert.equal(finding?.costMs, 56); + assert.equal(finding?.component, '#1'); +}); diff --git a/packages/react-native/src/react-devtools/react-profile-analysis.ts b/packages/react-native/src/react-devtools/react-profile-analysis.ts index 5af45a8decd..3d98b4f2d49 100644 --- a/packages/react-native/src/react-devtools/react-profile-analysis.ts +++ b/packages/react-native/src/react-devtools/react-profile-analysis.ts @@ -46,7 +46,7 @@ export type ReactProfileAnalysis = { commitCount: number; renderMs: number; slowCommitCount: number; - worstCommit: { index: number; durationMs: number } | null; + worstCommit: Pick | null; naming: RawReactProfile['naming']; /** Gaps in the evidence behind the findings, such as uninspected prop values. */ notes: string[]; @@ -182,7 +182,7 @@ type EagerMount = { index: number; count: number; costMs: number; - durationMs: number; + workMs: number; mounted: number; }; @@ -201,12 +201,12 @@ function eagerMountFindings(profile: RawReactProfile, commits: CommitProfile[]): group.actualMs += render.actualMs; groups.set(key, group); } - const durationMs = commits[index]!.durationMs; + const workMs = commits[index]!.workMs; for (const [key, group] of groups) { if (group.count < EAGER_MOUNT_INSTANCES) continue; - const costMs = Math.min(group.actualMs, durationMs); + const costMs = Math.min(group.actualMs, workMs); const entry = mountsByComponent.get(key) ?? { component: group.component, mounts: [] }; - entry.mounts.push({ index, count: group.count, costMs, durationMs, mounted }); + entry.mounts.push({ index, count: group.count, costMs, workMs, mounted }); mountsByComponent.set(key, entry); } }); @@ -219,7 +219,7 @@ function eagerMountFindings(profile: RawReactProfile, commits: CommitProfile[]): kind: 'eager-mount' as const, ...about(component), costMs, - evidence: `${worst.count} instances mounted at once in commit #${worst.index}, ${ms(worst.costMs)} of its ${ms(worst.durationMs)} (${worst.mounted} components mounted)${repeated}`, + evidence: `${worst.count} instances mounted at once in commit #${worst.index}, ${ms(worst.costMs)} of its ${ms(worst.workMs)} (${worst.mounted} components mounted)${repeated}`, fix: 'virtualize the list (FlatList/FlashList)', }; }); @@ -246,7 +246,7 @@ function chainedUpdaters( return componentsOf(profile, chained).filter((updater) => !isFrameworkPrimitive(updater.name)); } -function effectChainFindings(profile: RawReactProfile): Finding[] { +function effectChainFindings(profile: RawReactProfile, commits: CommitProfile[]): Finding[] { const chains = new Map(); for (let index = 1; index < profile.commits.length; index += 1) { const previous = profile.commits[index - 1]!; @@ -257,7 +257,7 @@ function effectChainFindings(profile: RawReactProfile): Finding[] { const key = componentKey(updater); const chain = chains.get(key) ?? { component: updater, count: 0, costMs: 0 }; chain.count += 1; - chain.costMs += commit.duration; + chain.costMs += commits[index]!.workMs; chains.set(key, chain); } } @@ -275,7 +275,7 @@ function effectChainFindings(profile: RawReactProfile): Finding[] { const STORM_MIN_COMMITS = 20; const STORM_MIN_RATE_PER_SECOND = 20; -function renderStormFindings(profile: RawReactProfile): Finding[] { +function renderStormFindings(profile: RawReactProfile, commits: CommitProfile[]): Finding[] { const byUpdater = new Map(); profile.commits.forEach((commit, index) => { for (const updater of componentsOf(profile, commit.updaters)) { @@ -293,7 +293,7 @@ function renderStormFindings(profile: RawReactProfile): Finding[] { const spanSeconds = Math.max((last - first) / 1000, 0.001); const rate = (indexes.length - 1) / spanSeconds; if (rate < STORM_MIN_RATE_PER_SECOND) continue; - const costMs = indexes.reduce((sum, index) => sum + profile.commits[index]!.duration, 0); + const costMs = indexes.reduce((sum, index) => sum + commits[index]!.workMs, 0); findings.push({ kind: 'render-storm', ...about(component), @@ -366,8 +366,7 @@ function explainedMs( /** The app component to cut work under: the updater when it holds the commit, else the deepest holder. */ function subtreeOwner(commit: CommitProfile): CommitComponent | undefined { const covering = commit.components.filter( - (entry) => - !isFrameworkPrimitive(entry.name) && entry.actualMs >= commit.durationMs * SUBTREE_SHARE, + (entry) => !isFrameworkPrimitive(entry.name) && entry.actualMs >= commit.workMs * SUBTREE_SHARE, ); return ( covering.find((entry) => commit.updaters.some((updater) => sameComponent(updater, entry))) ?? @@ -396,8 +395,8 @@ function slowCommitFinding(commit: CommitProfile): Finding { return { kind: 'slow-commit', ...(component ? about(component) : { component: `#${commit.index}` }), - costMs: commit.durationMs, - evidence: `commit #${commit.index} took ${ms(commit.durationMs)} rendering ${commit.rendered} components${mounted}${inside}${trigger}; most time in ${heaviest.join(', ')}`, + costMs: commit.workMs, + evidence: `commit #${commit.index} took ${ms(commit.workMs)} rendering ${commit.rendered} components${mounted}${inside}${trigger}; most time in ${heaviest.join(', ')}`, fix: `render less ${owner ? `under ${owner.name} ` : ''}per update (memoize, virtualize, or defer)`, }; } @@ -409,13 +408,13 @@ function slowCommitFindings( ): Finding[] { const explained = explanations(earlier); return commits - .filter((commit) => commit.durationMs >= SLOW_COMMIT_MS) + .filter((commit) => commit.workMs >= SLOW_COMMIT_MS) .filter( (commit) => explainedMs(profile, profile.commits[commit.index]!, explained) < - commit.durationMs * EXPLAINED_SHARE, + commit.workMs * EXPLAINED_SHARE, ) - .sort((a, b) => b.durationMs - a.durationMs) + .sort((a, b) => b.workMs - a.workMs) .slice(0, SLOW_COMMIT_FINDING_LIMIT) .map(slowCommitFinding); } @@ -443,9 +442,9 @@ export function analyzeReactProfile( ): ReactProfileAnalysis { const profile = chronological(recorded); const { components, commits } = summarizeRenders(profile, propKindsById); - const slowCommits = commits.filter((commit) => commit.durationMs > FRAME_BUDGET_MS); + const slowCommits = commits.filter((commit) => commit.workMs > FRAME_BUDGET_MS); const worst = commits.reduce( - (current, commit) => (current && current.durationMs >= commit.durationMs ? current : commit), + (current, commit) => (current && current.workMs >= commit.workMs ? current : commit), null, ); @@ -464,10 +463,10 @@ export function analyzeReactProfile( findings.push(...perComponent); } findings.push(...eagerMountFindings(profile, commits)); - findings.push(...effectChainFindings(profile)); - findings.push(...renderStormFindings(profile)); + findings.push(...effectChainFindings(profile, commits)); + findings.push(...renderStormFindings(profile, commits)); findings.push(...slowCommitFindings(profile, commits, findings)); - const renderMs = commits.reduce((sum, commit) => sum + commit.durationMs, 0); + const renderMs = commits.reduce((sum, commit) => sum + commit.workMs, 0); const costFloorMs = Math.max(MIN_FINDING_COST_MS, renderMs * MIN_FINDING_COST_SHARE); const significant = findings .filter((finding) => finding.costMs >= costFloorMs) @@ -478,7 +477,9 @@ export function analyzeReactProfile( commitCount: commits.length, renderMs, slowCommitCount: slowCommits.length, - worstCommit: worst ? { index: worst.index, durationMs: worst.durationMs } : null, + worstCommit: worst + ? { index: worst.index, durationMs: worst.durationMs, workMs: worst.workMs } + : null, naming: profile.naming, notes, components, diff --git a/packages/react-native/src/react-devtools/react-profile-format.test.ts b/packages/react-native/src/react-devtools/react-profile-format.test.ts index 364dd32d148..d5cb357c2d3 100644 --- a/packages/react-native/src/react-devtools/react-profile-format.test.ts +++ b/packages/react-native/src/react-devtools/react-profile-format.test.ts @@ -47,7 +47,7 @@ function analysis(overrides: Partial = {}): ReactProfileAn commitCount: 4, renderMs: 96, slowCommitCount: 2, - worstCommit: { index: 2, durationMs: 41.5 }, + worstCommit: { index: 2, durationMs: 12, workMs: 41.5 }, naming: 'operations', notes: [], components: [component('Chart'), component('Row', { renders: 9, instances: 3, selfMs: 9 })], @@ -56,6 +56,7 @@ function analysis(overrides: Partial = {}): ReactProfileAn index: 0, atMs: 0, durationMs: 10, + workMs: 10, rendered: 3, mounts: 0, updaters: [{ name: 'List', kind: 'function' }], @@ -64,7 +65,8 @@ function analysis(overrides: Partial = {}): ReactProfileAn { index: 1, atMs: 900, - durationMs: 41.5, + durationMs: 8, + workMs: 41.5, rendered: 30, mounts: 30, updaters: [], @@ -189,6 +191,7 @@ test('a commit entry without recorded changes says its cause is unrecorded', () index: 3, atMs: 1200, durationMs: 20, + workMs: 20, rendered: 2, mounts: 0, updaters: [], diff --git a/packages/react-native/src/react-devtools/react-profile-format.ts b/packages/react-native/src/react-devtools/react-profile-format.ts index f8344cf0f12..bac9af0f375 100644 --- a/packages/react-native/src/react-devtools/react-profile-format.ts +++ b/packages/react-native/src/react-devtools/react-profile-format.ts @@ -20,7 +20,7 @@ function headline(analysis: ReactProfileAnalysis): string { ]; if (analysis.worstCommit && analysis.slowCommitCount > 0) { parts.push( - `${analysis.slowCommitCount} over ${FRAME_BUDGET_MS}ms (worst #${analysis.worstCommit.index} ${ms(analysis.worstCommit.durationMs)})`, + `${analysis.slowCommitCount} over ${FRAME_BUDGET_MS}ms (worst #${analysis.worstCommit.index} ${ms(analysis.worstCommit.workMs)})`, ); } return parts.join(', '); @@ -126,9 +126,9 @@ function componentDetail(analysis: ReactProfileAnalysis, component: ComponentPro if (component.costliestCommits.length > 0) { const commits = component.costliestCommits.map(({ index, selfMs }) => { const commit = analysis.commits[index]; - return `#${index} ${ms(selfMs)}${commit ? ` of ${ms(commit.durationMs)}` : ''}`; + return `#${index} ${ms(selfMs)}${commit ? ` of ${ms(commit.workMs)}` : ''}`; }); - lines.push(`its costliest commits (self time of commit duration): ${commits.join(', ')}`); + lines.push(`its costliest commits (self time of total render work): ${commits.join(', ')}`); } return lines; } @@ -154,14 +154,14 @@ function commitLine(commit: CommitProfile): string { ? ` <- ${commit.updaters.map((updater) => updater.name).join(', ')}` : ''; const mounts = commit.mounts > 0 ? ` (${commit.mounts} mounted)` : ''; - return `#${commit.index} +${seconds(commit.atMs)} ${ms(commit.durationMs)} ${commit.rendered} rendered${mounts}${trigger}`; + return `#${commit.index} +${seconds(commit.atMs)} ${ms(commit.workMs)} ${commit.rendered} rendered${mounts}${trigger}`; } /** Every commit in order, or the slowest `limit` of them, still in order. */ export function listedCommits(analysis: ReactProfileAnalysis, limit: number): CommitProfile[] { if (analysis.commits.length <= limit) return analysis.commits; return [...analysis.commits] - .sort((a, b) => b.durationMs - a.durationMs) + .sort((a, b) => b.workMs - a.workMs) .slice(0, limit) .sort((a, b) => a.index - b.index); } diff --git a/packages/react-native/src/react-devtools/react-profile-renders.ts b/packages/react-native/src/react-devtools/react-profile-renders.ts index 409618ffbe3..8d6e4f49711 100644 --- a/packages/react-native/src/react-devtools/react-profile-renders.ts +++ b/packages/react-native/src/react-devtools/react-profile-renders.ts @@ -131,7 +131,10 @@ export type CommitProfile = { index: number; /** Milliseconds since the first commit of the profile. */ atMs: number; + /** Duration of the largest updated subtree, as reported by React DevTools. */ durationMs: number; + /** Total render work, including fibers without component names. */ + workMs: number; rendered: number; mounts: number; updaters: ComponentId[]; @@ -319,6 +322,10 @@ export function selectPropKindRequests(profile: RawReactProfile): PropKindReques function summarizeCommits(profile: RawReactProfile): CommitProfile[] { const origin = profile.commits[0]?.timestamp ?? 0; return profile.commits.map((commit, index) => { + let workMs = 0; + for (let offset = 2; offset < commit.fibers.length; offset += 3) { + workMs += commit.fibers[offset]!; + } const byComponent = new Map(); let rendered = 0; let mounts = 0; @@ -345,6 +352,7 @@ function summarizeCommits(profile: RawReactProfile): CommitProfile[] { index, atMs: Math.round(commit.timestamp - origin), durationMs: commit.duration, + workMs, rendered, mounts, updaters: componentsOf(profile, commit.updaters), diff --git a/src/commands/schema/cli-help.ts b/src/commands/schema/cli-help.ts index 03741cbceff..d2fcccad4cc 100644 --- a/src/commands/schema/cli-help.ts +++ b/src/commands/schema/cli-help.ts @@ -297,6 +297,7 @@ Profiling loop: Findings: slow-render: the component's own render is expensive. memo-defeated: a memoized component often re-renders because props change identity. parent-cascade: the component often re-renders with unchanged props, state, and context when its owner renders. context-cascade: most of the component's renders come from context changes. effect-chain: the component triggers a follow-up commit right after rendering, likely state set in an effect. render-storm: one component commits many times per second. eager-mount: hundreds of instances mount in one commit. slow-commit: a commit of three frames or more that other findings leave mostly unexplained. + Commit workMs sums fiber self times and determines render time and slow commits. durationMs is the largest updated subtree. Timings come from development builds and run slower than release builds; compare runs instead of reading absolute numbers. Rules: diff --git a/website/docs/docs/debugging-profiling.md b/website/docs/docs/debugging-profiling.md index 32092dc8586..47457cef0e0 100644 --- a/website/docs/docs/debugging-profiling.md +++ b/website/docs/docs/debugging-profiling.md @@ -77,6 +77,8 @@ agent-device react-devtools profile report agent-device react-devtools profile commit ``` +In commit JSON, `workMs` sums each fiber's own render time, including work spread across sibling subtrees. The summary adds these totals into `renderMs` and uses them to identify slow commits. `durationMs` records the duration of the largest updated subtree. + Without an argument, `report` lists components by self time with why they rendered, and `commit` lists the commits in order. Profiling works with development builds of React Native 0.74 and later, including Expo, and is verified on Android emulators and iOS simulators. It connects to the app through the Metro dev server, so the app, Metro config, and Babel config need no changes. If several apps use the same dev server, pass `--app `. If one app runs on several devices connected to the same dev server, pass `--metro-device ` with a device name the error lists. If the dev server is not the session's Metro server or `localhost:8081`, pass `--metro-port` and `--metro-host`.