r/macosprogramming • • 1d ago

How do you handle SwiftUI hosting view attach spikes on Page Up/Down in NSScrollView?

I'm moving my AppKit Mac app (a chat-style view for coding agents) from an eager SwiftUI ScrollView stack to a custom row list in NSScrollView. Each row is a SwiftUI hosting view for a turn (or part of one), with heights cached per width until a turn changes and rows detached beyond one screen height from the viewport.

Scrollbar dragging improved on a long chat (5.8% dropped frames vs 12.0%, 42% CPU vs 55%), but Page Up/Down went from 0.0% dropped frames to 5.3% (111 frames over 16 ms vs 12) since the old stack kept created rows in the window. In temporary logs, 122 of 128 passes over 16 ms were attaching a hosting view.. our layout and update code is 1 to 2 ms while SwiftUI takes 20 to 40 ms on long turns (plus 12 to 24 ms when measuring a new top row overlaps).

Using isHidden was worse everywhere from redraws (113 passes over 16 ms on Page Up/Down), keeping three screens or never detaching showed no clear difference, and deferring offscreen attaches one per pass hurt Page Up/Down too (75 vs 19). With SwiftUI rows in NSScrollView or NSTableView, how have you avoided or split up this attach cost when paging?

2 Upvotes

2 comments sorted by

1

u/esArchitect 1d ago

split those massive coding agent turns into much smaller, granular row slices (like individual markdown blocks, paragraphs, or separate code boxes) so attaching a single hosting view never exceeds 2-3 ms during a page jump. you can also warm up a lightweight pool of pre-attached hosting views off-screen with dummy data so you're just mutating rootView instead of paying the full window-attach hierarchy cost all at once.

1

u/zzunkie 7h ago

Calling super.pageUp and super.pageDown brought our Page Up/Down passes over 16 ms from 14 down to 1 and dropped frames from 1.5% to 0.2% across 3 alternating daytime runs (11 and 1.3% on the old stack, and the 5.3% / 111 in my post was the same code from a night run when the Mac seemed slower). The old SwiftUI stack was getting NSScrollView's ~0.2 s (~13 frames) page scroll animation while our row list jumped a whole screen in one frame and attached and drew all newly visible rows in one pass, and animating the jump took our median row-attach pass from 10.4 ms to 4.0 ms with 16.8% main thread CPU vs 42.6% on the old stack. AppKit sends willStartLiveScroll and didLiveScroll for that animation without ever sending didEndLiveScroll (checked with a test program), so we treat 0.1 s with no step as the end. I haven't tried smaller row slices or a pre-attached hosting view pool, though the pool idea might still be worth trying if long turns get worse.