ikieEngineeringGet started
All posts

iOSSwiftUIPerformance

While you swipe, only one thing should change

Every swipe in ikie's week view froze the screen for a moment. Instead of polishing drawing code, we used page values and a UIKit pager to shrink how much gets recomputed on each change.

한국어
Before
After

One frame = 8.3ms

One cell is one frame on a 120Hz display (8.3ms). A long cell means the screen sat still for that long. The longest stall of a week-view swipe, measured on the Mac simulator with real account data.

ikie's home screen is a calendar. A week strip sits on top and a timeline below. The top of the timeline is a header that holds the dates and all-day events, and you swipe sideways to reach the next week. People do this dozens of times a day, so when it stutters, the whole app feels heavy.

One day, a screen recording from a real iPhone showed something odd. At the moment a finger touched down and the moment it lifted, the screen held still for 17–50ms (1–3 frames of the recording) and then jumped. Dragging itself was smooth. Only the start and the end hitched.

We measured: it wasn't heavy, it was wide

Our first guess was slow drawing. But when we ran a Release build on the Mac simulator against a real account and split main-thread time by moment, the story changed.

SwipeTouch downEach drag frameLift offBuilding a new page
Week timeline45–50ms8–12ms52–85ms36–60ms
Day timeline~50ms7–13ms29–78ms26–38ms
Month calendar34–91ms8–42ms32–70ms40ms

41% of the busy time was SwiftUI's graph update (AttributeGraph). Our own block-drawing code was a small share. The problem was how far each change reached. Lifting a finger changed three pieces of state at the top of the home screen in turn (the selected day, the header height, the scroll position). So a single lift re-ran the home screen 3–4 times, and along the way pages and headers were rebuilt 15–18 times and the hidden copies used to measure header height 13–16 times.

The cause was structural

There were traces of fixing the same symptom place by place. The home screen files carried 44 comments like "this used to stutter" or "this was recomputed." Plug one hole and another opened. So this time we looked at the structure, not the symptom.

Before

Home screen stateselected day · header height · scroll
3 pages × 7 columns3 hidden header copies4 week-strip rows

All recomputed on every lift

After

One pager positionUIScrollView contentOffset
5 prebuilt pages (reused)Page value WeekPageWeek strip reads one small cell

Written once after it settles

There were four causes.

  1. Swiping changed state for the whole home screen. The selected day, the header height and the scroll fix-up all lived at the top of home, so every lift re-ran all of it.
  2. Pages lived inside the home graph. Timeline pages were drawn by closures home built, so any change to home recomputed all three pages.
  3. Pages weren't built ahead. A hand-built three-page carousel built the next week page (7 columns, 19 hour labels, a header) on the spot when it settled (36–60ms). Swipe quickly and that work overlapped the next touch, reaching 100–130ms.
  4. The week strip that follows along was expensive. Every time it followed the timeline, it rebuilt its rows and recomputed the whole calendar.

Two principles

Before fixing anything, we wrote the principles down.

While you swipe, only the pager's position changes. Committing the selected day, header height, scroll fix-up, and data that arrived mid-swipe all happen once, after it settles.

Pages draw from values, are built ahead, and are reused. A page redraws only when its own dates or that day's events change.

Pages as values: WeekPage

First, everything needed to draw one timeline page went into a single pure computation: placed blocks per day column, folded night hours, visible hour lines, all-day rows, the empty-day hint. The day view is the same value with one day.

/// What one timeline page (1 column for a day, 7 for a week) draws. Built once when the event data changes; the page view only draws it
struct WeekPage: Equatable, Sendable {
    struct Column: Equatable, Sendable {
        let day: String
        let placed: [TimelineLayout.Placed]   // placed blocks (grouped down to +N)
        let allDay: [Schemas.Entry]
        // …
    }
}

Block layout isn't recomputed here. It calls the existing layout (30-minute rows, overlaps side by side, +N grouping) and only bundles the result. Being Equatable, the same input yields the same value, and a page view whose value didn't change doesn't redraw. We kept state like "is this the visible page" out of the value. Derived state tied to the selected day would flip two pages and redraw them on lift.

Leave swiping to the OS: a UIKit pager

ikie is a SwiftUI app, but the pager itself is now horizontal paging on UIScrollView. Neighboring pages that follow your finger, stopping one page at a time, catching a settling page and dragging on from where it is: the OS already gets that feel right. We deleted the code that imitated re-grabbing with a spring.

final class PagerScroll: UIScrollView, UIScrollViewDelegate {
    /// Pages kept built on each side
    static let ahead = 2
    override init(frame: CGRect) {
        super.init(frame: frame)
        isPagingEnabled = true
        isDirectionalLockEnabled = true
        delaysContentTouches = false
        // …
    }
}

Page views stay SwiftUI through UIHostingConfiguration. Five are built ahead, two on each side of the current page, and a view that drifts far away is reused for a new page. Dates are computed from page numbers, so you can swipe forever; near the end of the scroll range the reference point moves.

When to commit is policy

"What changes on lift, and what waits until it settles" isn't scattered through view code; it's declared once as app policy. ikie's web and iOS apps are the same app, so rules like this are written as data in packages/policy, and each app reads them with its own interpreter.

paging: {
  // when the selected-day marker (circle, haptic) moves
  selectOn: { value: "release", platforms: both },
  // when the selected day is written and the timeline's day, header height and scroll catch up
  commitOn: { value: "settle", platforms: both },
  // data received mid-swipe is held and applied after it settles
  holdData: { value: true, platforms: both },
}

On lift, the circle and haptic jump to the day it will land on. That circle is computed from where the pager will stop, so no second selected day is stored. The selected day is one fact, saved once after the pager settles. The web (TypeScript) and iOS (Swift) interpreters run the same scenario file, so cases like "grabbing the pager again before it settles doesn't save the selected day" hold identically in both apps.

Measured at every step

We didn't change it all at once. One PR per step, each with numbers from the same probe (debug code that times the main thread at each moment).

  1. PolicyDeclare 'commit after settle' in the paging policy
  2. APage value WeekPage (pure computation) and tests
  3. BTimeline on a UIKit pager, pages drawn from values
  4. CConfine the week strip's following to one small cell
  5. DSplit the settle frame, cut redraws per write, performance tests

After B, lifting a finger no longer rebuilt home and the three pages (the probe counted zero recomputes of the home screen, pages, and day columns on lift). Touch down, though, stayed at 40–56ms. That was the week strip redrawing as it started following. In C, once the strip read the pager position from a single small cell, it dropped to 1–4ms.

D split up the work done the moment the pager settles. On settle, only the new current page swaps in right away; retiring the old page and building the page two ahead happen one per frame after that. The week strip keeps seven rows keyed by week date, three on each side of the current week, so swiping again builds no new rows. Separately from swiping, checking off a single to-do in the week view used to reconfigure pages 43 times; it's now 10. Each time a page was reconfigured it registered another observer on the event data, and they piled up; now each page keeps exactly one.

Demo dataBeforeBCD
Week touch down22–76ms40–56ms1–4ms0–4ms
Week lift off46–147ms6–8ms4–5ms0–6ms
Week settle26–113ms12–19ms10–24ms10–13ms

Finally, we measured again with the same real account data where we first found the cause.

BeforeAfterOne frame 8.3ms
Show as table
MomentBeforeAfter
Week touch down45–50ms0–5ms
Week lift off52–85ms5–7ms
Settle, new page36–60ms10–14ms
Mac simulator with real account data (a packed calendar), Release build, same probe, swiping slowly 5 times and rapidly 6 times. Before is wall-clock time and after is main-thread CPU time (on a Mac running several simulators, wall-clock time stretches several-fold, so we switched what we measure). The dashed line is one 120Hz frame (8.3ms).

In the week view, late frames while swiping went from 1–3 per swipe to zero. Touch down and lift off now fit inside a single frame.

Faster, but off

Every number improved, but using it on a real iPhone turned up something else.

What we sawSinceFixed in
On settle, the selected-day circle jumped back to the old day, then moved againAfter the rework#707
The incoming day's all-day row was missing, then popped in on settleAfter the rework#707
Swiping fast and repeatedly, the week strip and circle only jumped at the very endAfter the rework#713 #719
After a swipe settled, the timeline jumped up or downSide effect of a post-rework fix (#818)#847

The causes came down to one thing. We only measured speed. Touch down, lift and settle times dropped sharply, but we never measured "what shows where". Places where we removed a read or write to go faster changed behavior. For example, one line that cleared the "landing day" on re-grab kept the circle on the first day through a run of swipes, then jumped it at the end.

The old structure also gave us things for free. The old SwiftUI pager kept its pages in one row (HStack), so their heights and positions moved together. Moving to UIKit meant rebuilding each of those, and nothing listed what had to be kept.

So before fixing, we wrote down what must hold, as tests. A drag is split into ten frames, mixed like a person would do it with lifts, deceleration, re-grabs before settling and reversals, and every frame checks two things. While swiping, the position the week strip reads must equal the timeline's, and after lifting, the selected day shown must be the page last released. Run against the code before the fix, 173 checks broke (127 position, 44 circle). We also measure how far the timeline moves on its own after settling and fail anything over 4pt. Before the fix, the day view with the month calendar open drifted 380pt and 200pt.

Before changing a structure, write down what the old one did as invariants checked every frame. A speed table alone lets those break unnoticed.

Keeping it fixed

You fix performance once, but you have to keep it fixed for much longer. So we pinned the fix down with tests.

  • Performance tests: swipe the week and day views rapidly 20 times, measured with XCTHitchMetric and the probe. The goal is touch down and lift off within one 60Hz frame and settling within two. Demo data only exists in Debug builds, so the tests run in Debug with time limits doubled, and allow at most one late frame while moving. The probe measures main-thread CPU time rather than wall-clock time, so numbers stay steadier on a Mac running several simulators.
  • Layer tests: page view files can't read home's selected day, visible days, or event data. If someone reaches into home state from a page for convenience, CI stops it.
  • Policy scenarios: for each moment of a swipe (dragging, lift, settle), both apps test what they hold and what they commit, with the same cases.
  • Pager tests: building two pages ahead and reusing them, committing once on settle, continuing a drag without committing when re-grabbed before settling.
  • Invariant tests: the person-like swipes above check, every frame, the week strip against the timeline, the circle after lifting, and how far the timeline moves on its own after settling.

What's left

Every number in this post was measured on the Mac simulator. It's slower than a device, but we assumed the ratios hold and used it to pick the direction. We don't have Instruments numbers from a real iPhone yet; on the device, recordings made while using the app found the glitches above.

In the day view, saving the selected day once the pager settles is still slow (65–100ms). The pager has already stopped, so it doesn't overlap the swipe, but it recomputes home, the toolbar and the week rows together, and we'll shrink it with the same principles.

What we learned

  • Measure by moment, not by hunch. "Drawing is slow" and "the day view is fine" were both wrong. Splitting touch down, drag, lift and new page showed the cause.
  • Change less rather than run faster. We barely made any single step cheaper. We shrank how far each change reaches.
  • Leave the feel to the OS. UIScrollView re-grabs more precisely than our spring imitation. What we build by hand is narrowed to what the OS doesn't give (holding pages ready).
  • Measure position along with speed. PRs that made swiping faster also knocked the circle and week strip out of place. Per-frame invariants filled that gap.
  • Put rules in one place, as data. Declaring when to commit as policy makes web and iOS do the same thing at the same moment, tested by the same scenarios.

Chasing the stutter when folding and unfolding the calendar, with the same methods, is in the calendar fold post.

The ikie teamikie is a calendar for your events and to-dos in one place. Here we write about the problems we run into while building it, and how we solve them.