Skip to content

View hierarchy: fewer allocations per node in the walk and the writer - #30

Merged
krassx merged 4 commits into
perf/view-hierarchy-frame-budgetfrom
perf/view-hierarchy-alloc-trim
Nov 10, 2026
Merged

krassx merged 4 commits into
perf/view-hierarchy-frame-budgetfrom
perf/view-hierarchy-alloc-trim

Conversation

@krassx

@krassx krassx commented Nov 10, 2026

Copy link
Copy Markdown
Contributor

Stacked on #29.

  • one transform matrix per element depth, reused by every node at that depth, instead of clone() per node. Safe because a node's matrix is read only while its own subtree is visited, and everything below a node is visited at a greater depth than the node (a provider of data does not add a level, but the render node below it is still deeper than the render ancestor whose matrix it reads);
  • child and overlay lists created only when used (most nodes are leaves);
  • the options object written without a temporary list;
  • the template is no longer joined just to read its length.

Same output: the payload (render()), node count, bounds and truncation are byte for byte identical to the previous builder on five trees (Material screen with tabs and 40 cards, options such as opacity/secure/clickable/image/rotate, an OverlayPortal, a 300-row eager list, a node-capped list); the existing builder tests, including the differential tests of #26, pass.

Measured (profile build, median of 25, unlimited limits, one run each on the same day, before then after):

Screen Android phone iPhone XS
lazy 50 rows 8.7 → 7.5 ms 0.68 → 0.65 ms
lazy 1000 rows 9.0 → 6.9 ms 0.67 → 0.65 ms
eager 1000 rows 30.2 → 25.8 ms 3.57 → 3.32 ms
eager 3000 rows 83.6 → 82.1 ms 10.0 → 9.7 ms

Run-to-run noise on the same code is about ±5%, so the iPhone gains and the 3000-row case are within noise; the Android lazy and 1000-row gains are not. The research agent measured 0-5% on an emulator, the phone gains more.

Checks: flutter analyze, full flutter test.

🤖 Generated with Claude Code

One transform matrix per element depth is reused by every node at that depth
instead of a clone per node (a node's matrix is only read while its own subtree
is visited, and everything below it is at a greater depth). Child and overlay
lists are created only when used. The options object is written without a
temporary list, and the template is not joined just to read its length.

The payload is byte for byte the same on five trees (Material screen, options,
overlay, eager list, node cap) against the previous builder. Profile build on
devices, one run each: a lazy list 8.7-9.0 to 6.9-7.5 ms on the Android phone,
an eager 1000-row list 30.2 to 25.8 ms, the iPhone XS 4-7% faster.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WeiJxNbNUdWru1zs68bYV8
Change-Id: I6a27fc87856754ea4617dc41aa3984d1b722ef76
@coderabbitai

coderabbitai Bot commented Nov 10, 2026 •

Copy link
Copy Markdown

Explain Change →

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 59 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 0fdfc900-0110-45f8-a86a-2c812ac88d58
Commits

Reviewing files that changed from the base of the PR and between d29939a and c54dd2e.

Files selected for processing: 3

  • PLAN.md
  • doc/view-hierarchy.md
  • lib/src/view_hierarchy/hierarchy_builder.dart

No actionable comments were generated in the recent review.

Summary

Summary by CodeRabbit

  • Performance
    • View-hierarchy processing now uses fewer temporary allocations and avoids unnecessary intermediate data, improving measured processing times while keeping the generated payload unchanged.
  • Tests
    • Verified attachments, network data, and logs on iPhone XS and iPhone 16 Pro using a LAN-hosted test API. Log timestamps matched capture times; the iPhone 16 Pro Wi-Fi test was unsuccessful.

The view-hierarchy walker now allocates child lists on demand, reuses transform matrices by depth, and appends deferred nodes after visiting a render node’s children. The writer tracks output length and emits node options and bounds without temporary collections. Snapshot size validation uses the writer’s returned length. Documentation records updated performance measurements and device verification results, including byte-for-byte identical payload output.

Possibly related issues

Possibly related PRs

Change: Refactor

Merge Risk: Minimal · previous review d2993

No merge-blocking issue was identified in the allocation changes.

Pre-merge checks: Passed 5

Check name Status Explanation
Title check Passed The title clearly summarizes the main change: reducing allocations in the view-hierarchy walk and writer.
Description check Passed The description explains the allocation changes, reports output-equivalence checks, and includes performance measurements related to the changeset.
Docstring Coverage Passed No eligible functions found in the changed files. Skipping docstring coverage check. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentat…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

No eligible functions found in the changed files. Skipping docstring coverage check. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 0 functions across 0 files. (3 skipped: 3 unsupported.)

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: d524f855-2a19-4a72-a5a8-5b75d510abcd
Commits

Reviewing files that changed from the base of the PR and between b07584f and d29939a.

Files selected for processing: 3

  • PLAN.md
  • doc/view-hierarchy.md
  • lib/src/view_hierarchy/hierarchy_builder.dart

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

@claude

claude Bot commented Nov 10, 2026 •

Copy link
Copy Markdown

Claude finished @krassx's task in 36s —— View job


Review of #30: fewer allocations per node in the walk and the writer

I found no real issues. I read the diff against the surrounding code in hierarchy_builder.dart. I did not run flutter analyze or flutter test; this review is from reading the code.

Overall risk: Low
Merge recommendation: Approve, once the author's flutter analyze and flutter test run is confirmed green on CI.

What I checked

  • Matrix pool (_pool(depth)). The "greater depth" invariant holds in the code, not only in the PR text.
    • A render node at depth d writes pool(d) and passes it to its children as ctx.toView.
    • Every descendant is visited at depth + 1 or deeper. Render nodes and composites both call _children(..., depth + 1). An InheritedElement keeps the depth, but it sits at a depth already at least dA + 1, so nothing below a render node can write pool(dA) while that node is open.
    • Siblings at the same depth run one after another, and a node's matrix is not read after its subtree finishes. clip.intersect(transformRect(ctx.toView, …)) runs before the subtree, and the Rects stored on nodes are fresh values.
    • The OverlayPortal path (_placeViaRenderAncestors) still returns a fresh Matrix4, so a pooled matrix never ends up as ctx.toView of a node that lives elsewhere in the tree.
    • _scratch in _containedBelow is a separate object from the pool.
    • The pool belongs to one _Walker and a walker is not shared, so there is no reentrancy.
  • Lazy lists.
    • children returns a const empty list for leaves. The only caller that mutates children is addChild, and a repo grep found no other .children.add or .late use.
    • flushLate appends in the same order as the old addAll(late) + clear().
    • Late nodes are flushed before the node is attached to its parent, as before.
  • Writer.
    • The options object keeps the old order (secure, clickable, alpha, content_kind) and the same braces and commas.
    • The hasAlpha check matches the old alpha != null && alpha.isFinite.
    • The bounds adds are in the same order.
    • _length accumulated in _cut() equals segments.join().length, so the maxBytes check is unchanged.
  • Docs. The PLAN.md and doc/view-hierarchy.md additions state their numbers as "one run each" and say the gains are within noise where they are, which matches the PR body. No pinned-API, wire, or drift-guard surface is touched, so none of the CLAUDE.md guards need changing.

Optional follow-up (P3, not blocking)

The "same payload" evidence is five trees compared against the old builder. That comparison cannot be repeated once this lands, and I did not find a test aimed at the aliasing invariant itself. A cheap guard would be a golden payload for a deeply nested tree that mixes InheritedElements, composites, an OverlayPortal, and sibling transforms at equal depth (Transform, Positioned in a Stack). A regression such as forgetting depth + 1 in a new call site would then change the output.

Positives

  • The change is small, local, and keeps the output byte-identical.
  • The depth-pool invariant is documented at the _pool site.
  • The measured gains are stated honestly, including which ones are within noise.

…chy-alloc-trim

Change-Id: I44d288ba960a1e64c47bba72f563f0c92b2623f1

# Conflicts:
#	PLAN.md
#	doc/view-hierarchy.md
@claude

claude Bot commented Nov 10, 2026 •

Copy link
Copy Markdown

Claude finished @krassx's task in 26s —— View job


Review of #30: fewer allocations per node in the walk and the writer (re-run on push)

I found no real issues, and nothing new compared with my earlier review. The only change since then is the merge of the base branch (d29939a), which brings in no new code from this PR. I re-read the diff and the surrounding walker code. I did not run flutter analyze or flutter test.

Overall risk: Low
Merge recommendation: Approve, once CI is green. The base PR #29 has to merge first, because this one is stacked on it.

Re-checked this round

  • Matrix pool (_pool(depth)). Every _children call passes depth or depth + 1. Only InheritedElement keeps the same depth. A render node at depth d writes only pool(d), and its subtree runs at depth d + 1 or deeper. So a matrix handed to a child as ctx.toView always comes from a strictly lower depth than the child's own slot. _pool(depth)..setFrom(ctx.toView) therefore never copies a matrix onto itself.
  • Reads of ctx.toView. The clip intersect, transformRect and _isAffine all run before the subtree is visited. Nothing reads a node's matrix after the node's children have run.
  • Other matrices. The root context and the OverlayPortal path (_placeViaRenderAncestors) still use fresh matrices. _scratch is separate from the pool. The walk is synchronous, so there is no reentrancy.
  • Lazy lists. The only mutators left are addChild, addLate and flushLate; a grep of lib finds no other .children.add or .late use. The shared const empty list is never written to. flushLate keeps the old order, and it still runs before the node is attached to its parent.
  • Writer.
    • The options object keeps the same member order and separators, and the same condition (alpha != null && alpha.isFinite).
    • _length is the sum of the cut segments, which equals segments.join().length, so the maxBytes check is unchanged.
    • finish() now returns an int, and its only caller is updated.
  • Docs and guards. The PLAN.md and doc/view-hierarchy.md numbers match the PR body, including that they come from one run each. No pinned API, wire format or drift guard is touched, so CLAUDE.md requires no guard change.

Optional follow-up (P3, not blocking, same as before)

The "byte for byte identical" evidence comes from a one-off comparison against the old builder, and I found no test aimed at the depth-aliasing invariant itself. A golden payload for one tree that mixes InheritedElements, composites, an OverlayPortal and same-depth sibling transforms (Transform, Positioned in a Stack) would catch a future call site that forgets depth + 1.

Positives

  • The change is small and local, and the invariant is documented where the pool is defined.
  • The PR states honestly which measured gains are within noise.

…' into perf/view-hierarchy-alloc-trim

Change-Id: Ieee271d90d6134140d2f3bdea02dad7ab2af6be4
@claude

claude Bot commented Nov 10, 2026 •

Copy link
Copy Markdown

Claude finished @krassx's task in 23s —— View job


Review of #30: fewer allocations per node in the walk and the writer (re-run on push)

I found no real issues, and nothing new compared with my two earlier reviews. The only change since the last review is a merge of the base branch (5db0a3e). I re-read the diff and the walker code in hierarchy_builder.dart. I did not run flutter analyze or flutter test; this review is from reading the code.

Overall risk: Low
Merge recommendation: Approve once CI is green. Merge #29 first, because this PR is stacked on it.

Re-checked this round

  • Matrix pool (_pool(depth), line 475).
    • A render node at depth d writes only pool(d), and its ctx.toView always comes from an ancestor render node at a smaller depth d0 < d.
    • _children is called with depth + 1 from render nodes (lines 507 and 549) and from composites (line 423). Only InheritedElement keeps the depth (line 411), and it is already at a depth of at least d0 + 1.
    • So _pool(depth)..setFrom(ctx.toView) never copies a matrix onto itself, and no descendant writes pool(d0) while that node is open.
    • ctx.toView is read (clip intersect, transformRect, _isAffine, _containedBelow) only before the subtree is visited, and nodes keep Rect values, never matrices.
    • The OverlayPortal path (_placeViaRenderAncestors) still hands out a fresh Matrix4.
    • The walk is synchronous and the pool belongs to one walker, so there is no reentrancy.
  • Lazy lists. The only places that touch children are addChild, flushLate, the composite's read loop (line 425) and the writer's reads (lines 803 and 806). The shared const empty list is never written to, and flushLate keeps the old order.
  • Writer. The options object keeps the same member order, separators and condition (alpha != null && alpha.isFinite). _length is the sum of the cut segments, which equals segments.join().length, so the maxBytes check is unchanged.
  • finish() now returns int. I found no caller other than hierarchy_builder.dart:368 in lib/src/view_hierarchy. The two .finish() hits in test/device_harness_test.dart (lines 1253 and 1263) are a different type.
  • Docs and guards. The PLAN.md and doc/view-hierarchy.md numbers match the PR body, and both say one run each. No pinned API, wire format or drift guard is touched, so none of the CLAUDE.md guards need changing.

Optional follow-up (P3, not blocking, same as before)

The "byte for byte identical" evidence is a one-off comparison against the old builder, and I found no test aimed at the depth-aliasing invariant. A golden payload for one tree that mixes InheritedElements, composites, an OverlayPortal and same-depth sibling transforms (Transform, Positioned in a Stack) would catch a future call site that forgets depth + 1.

Summary

  1. Overall risk: Low.
  2. Merge recommendation: Approve once CI is green and View hierarchy: walk budget follows the frame while one is due #29 has merged.
  3. Most important issues to fix: none.
  4. Positives:
    • The change is small and local.
    • The depth invariant is documented at the pool.
    • The PR states plainly which measured gains are within noise.

…chy-alloc-trim

Change-Id: I04a9476b557f2b5cc7d9d0c8b230f6051599139a
@claude

claude Bot commented Nov 10, 2026 •

Copy link
Copy Markdown

Claude finished @krassx's task in 24s —— View job


Review of #30: fewer allocations per node in the walk and the writer (re-run on push)

I found no real issues, and nothing new compared with my three earlier reviews. The only change since the last review is a merge of the base branch (c54dd2e). The PR's own diff against origin/perf/view-hierarchy-frame-budget is unchanged (3 files, +78/−24). I re-read the diff and the walker code in hierarchy_builder.dart. I did not run flutter analyze or flutter test; this review is from reading the code.

Overall risk: Low
Merge recommendation: Approve once CI is green. Merge #29 first, because this PR is stacked on it.

Re-checked this round

  • Matrix pool (_pool(depth), line 475).
    • toView is written only at line 475, into pool(depth). The only matrices read at that point are ctx.toView (lines 475 and 481), which comes from a render ancestor at a smaller depth or from a fresh matrix. So setFrom never copies a matrix onto itself.
    • _children is called with depth + 1 at lines 507 and 549. toView is read (transformRect, _isAffine, _containedBelow) only before the subtree is visited. _Context objects and _Nodes hold no matrices, so nothing outlives the visit.
    • The root context (line 358) and the OverlayPortal path (_placeViaRenderAncestors, lines 680–692) still use fresh Matrix4s. _scratch is separate from the pool.
  • Lazy lists. The shared const empty list is never written to. addChild, addLate and flushLate are the only mutators, and flushLate keeps the old order. It still runs before the node is attached to its parent.
  • Writer. The options object keeps the same member order, separators and condition (alpha != null && alpha.isFinite). _length is the sum of the cut segments, which equals segments.join().length, so the maxBytes check is unchanged. finish() now returns int, and its only caller in lib is hierarchy_builder.dart:368.
  • Docs and guards. The PLAN.md and doc/view-hierarchy.md numbers match the PR body, and both say one run each. No pinned API, wire format or drift guard is touched, so CLAUDE.md requires no guard change.

Optional follow-up (P3, not blocking, same as before)

The "byte for byte identical" evidence is a one-off comparison against the old builder, and I found no test aimed at the depth-aliasing invariant. A golden payload for one tree that mixes InheritedElements, composites, an OverlayPortal and same-depth sibling transforms (Transform, Positioned in a Stack) would catch a future call site that forgets depth + 1.

Summary

  1. Overall risk: Low.
  2. Merge recommendation: Approve once CI is green and View hierarchy: walk budget follows the frame while one is due #29 has merged.
  3. Most important issues to fix: none.
  4. Positives:
    • The change is small and local.
    • The depth invariant is documented at the pool.
    • The PR states plainly which measured gains are within noise.

@krassx
krassx merged commit b415a38 into nextgen Nov 10, 2026
@krassx
krassx deleted the perf/view-hierarchy-alloc-trim branch November 11, 2026 17:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant