Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 26 additions & 2 deletions packages/react-native/src/index-react-profile.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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\)$/,
);
});

Expand Down Expand Up @@ -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', () => {
Expand All @@ -272,22 +272,22 @@ test('a component mounted eagerly in several commits is one finding costed acros
const tiles = repeat(250, (i) => 10 + i);
const elements: Record<number, [string, number?, number?]> = { 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');
assert.equal(rest.length, 0);
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$/);
});
Expand Down Expand Up @@ -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',
);
});
Expand Down Expand Up @@ -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',
);
});

Expand Down Expand Up @@ -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');
});
47 changes: 24 additions & 23 deletions packages/react-native/src/react-devtools/react-profile-analysis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export type ReactProfileAnalysis = {
commitCount: number;
renderMs: number;
slowCommitCount: number;
worstCommit: { index: number; durationMs: number } | null;
worstCommit: Pick<CommitProfile, 'index' | 'durationMs' | 'workMs'> | null;
naming: RawReactProfile['naming'];
/** Gaps in the evidence behind the findings, such as uninspected prop values. */
notes: string[];
Expand Down Expand Up @@ -182,7 +182,7 @@ type EagerMount = {
index: number;
count: number;
costMs: number;
durationMs: number;
workMs: number;
mounted: number;
};

Expand All @@ -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);
}
});
Expand All @@ -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)',
};
});
Expand All @@ -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<string, { component: ComponentId; count: number; costMs: number }>();
for (let index = 1; index < profile.commits.length; index += 1) {
const previous = profile.commits[index - 1]!;
Expand All @@ -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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Each matched updater receives the full commit workMs, so a commit with multiple updaters charges the same sibling work to every component's finding. Attribute work to the relevant updater or avoid per-component cost attribution when the commit has multiple updaters.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At packages/react-native/src/react-devtools/react-profile-analysis.ts, line 260:

<comment>Each matched updater receives the full commit `workMs`, so a commit with multiple updaters charges the same sibling work to every component's finding. Attribute work to the relevant updater or avoid per-component cost attribution when the commit has multiple updaters.</comment>

<file context>
@@ -257,7 +257,7 @@ function effectChainFindings(profile: RawReactProfile): Finding[] {
       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);
     }
</file context>

chains.set(key, chain);
}
}
Expand All @@ -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<string, { component: ComponentId; indexes: number[] }>();
profile.commits.forEach((commit, index) => {
for (const updater of componentsOf(profile, commit.updaters)) {
Expand All @@ -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),
Expand Down Expand Up @@ -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))) ??
Expand Down Expand Up @@ -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(', ')}`,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: workMs includes unnamed fibers, but rendered counts only fibers that commitRenders can resolve to profiled components. Qualify this count as profiled components or report a total fiber count so the evidence does not understate what rendered.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At packages/react-native/src/react-devtools/react-profile-analysis.ts, line 399:

<comment>`workMs` includes unnamed fibers, but `rendered` counts only fibers that `commitRenders` can resolve to profiled components. Qualify this count as profiled components or report a total fiber count so the evidence does not understate what rendered.</comment>

<file context>
@@ -396,8 +395,8 @@ function slowCommitFinding(commit: CommitProfile): Finding {
-    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)`,
   };
</file context>
Suggested change
evidence: `commit #${commit.index} took ${ms(commit.workMs)} rendering ${commit.rendered} components${mounted}${inside}${trigger}; most time in ${heaviest.join(', ')}`,
evidence: `commit #${commit.index} took ${ms(commit.workMs)} rendering ${commit.rendered} profiled components${mounted}${inside}${trigger}; most time in ${heaviest.join(', ')}`,

fix: `render less ${owner ? `under ${owner.name} ` : ''}per update (memoize, virtualize, or defer)`,
};
}
Expand All @@ -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);
}
Expand Down Expand Up @@ -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<CommitProfile | null>(
(current, commit) => (current && current.durationMs >= commit.durationMs ? current : commit),
(current, commit) => (current && current.workMs >= commit.workMs ? current : commit),
null,
);

Expand All @@ -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)
Expand All @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ function analysis(overrides: Partial<ReactProfileAnalysis> = {}): 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 })],
Expand All @@ -56,6 +56,7 @@ function analysis(overrides: Partial<ReactProfileAnalysis> = {}): ReactProfileAn
index: 0,
atMs: 0,
durationMs: 10,
workMs: 10,
rendered: 3,
mounts: 0,
updaters: [{ name: 'List', kind: 'function' }],
Expand All @@ -64,7 +65,8 @@ function analysis(overrides: Partial<ReactProfileAnalysis> = {}): ReactProfileAn
{
index: 1,
atMs: 900,
durationMs: 41.5,
durationMs: 8,
workMs: 41.5,
rendered: 30,
mounts: 30,
updaters: [],
Expand Down Expand Up @@ -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: [],
Expand Down
10 changes: 5 additions & 5 deletions packages/react-native/src/react-devtools/react-profile-format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(', ');
Expand Down Expand Up @@ -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;
}
Expand All @@ -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);
}
Expand Down
Loading
Loading