·9 min read

Capacitor app slow on iPhone: a 2 s freeze

My Capacitor game's home screen froze on iPhone each time a player came back to it. An unlock check that grew with progress, and 100 hidden carousel panels.

capacitorperformancejavascripttesting

Contents

The home screen of ASMR Logo Craft Block is a carousel of a hundred collections, ten levels each. It is React inside a Capacitor WebView, and on my iPhone it had started to feel heavy. Coming back from a level or from the Stats screen, home would appear and then sit there. Swiping between collections stuttered, and the next collection's pictures looked like they were loading again every time.

The Mac showed some of this, but players hold phones, so the first job was to measure on one.

Measuring on the phone, not the laptop

I had Claude Code write a small probe that drives the game on the iPhone over the Web Inspector protocol: tap Stats, tap back, then count the frames the WebView actually draws in the next 0.8 seconds. Same idea for one carousel step, counted over 0.65 seconds.

The first clean run, after a fresh launch:

stats->home 0 {"homeBackMs":305,"after":{"frames":2,"worst":541,"slow":1}}
stats->home 1 {"homeBackMs":157,"after":{"frames":20,"worst":124,"slow":3}}

An earlier run, made with popups still stacked under home from the probe's previous attempt, was much worse: two frames in 0.8 seconds, one of them 2,253 ms long, the next time 1,587 ms. That is the two-second freeze in the title. It is not a fair baseline, so the table at the end gives the whole range.

A carousel step drew between one and eight frames in its 0.65 seconds. One frame per step means the swipe did not animate at all; it jumped.

The phone also told me something the Mac never had. Sitting idle on home, doing nothing, the WebKit timeline showed a style recalculation of about 13 ms on almost every frame. That is most of a 60 Hz budget gone before anything happens.

Cause one: an unlock check that grows with progress

To see what was slow, the Mac is still the better tool, as long as you slow it down. A Chromium CPU profile of "Stats, back to home" under a 4× CPU slowdown, on a save about two dozen levels in:

== stats back -> home: 4496 ms wall, busy 3543 ms
    2009 ms  isUnlocked
    1076 ms  (program)
     149 ms  (anon)

Two seconds of a slowed-down CPU in one function. It lives in a shared progress package I use across games, and it answers "can the player open this level?". Here is its shape, simplified:

// Simplified from the real code: the shape, not the source.
function isUnlocked(progress, levels, level) {
  const index = levels.indexOf(level);
  let furthest = -1;
  for (let i = 0; i < levels.length; i++) {
    if (progress.completed.includes(levels[i])) furthest = i;  // scans the save
  }
  return index <= furthest + 2;  // the next level, plus one ahead
}

// The level picker asked it once per level, for all 1,000:
const entries = levels.map((id) => ({ id, unlocked: isUnlocked(progress, levels, id) }));

Each call walks the whole level list, and for each level walks the completed list. Called once per level, that is levels × levels × completed. With a thousand levels the first two factors are a million on their own, and the third starts at zero on a fresh save and grows every time the player wins.

And it ran every time home was built: after every level, after Stats, after a relaunch. Home is the screen a player comes back to after every single level.

The fix keeps the same rule and asks it once:

// Simplified: one pass over the save, one pass over the list.
function levelStates(progress, levels, lookahead = 1) {
  const done = new Set(progress.completed);
  let furthest = -1;
  levels.forEach((id, i) => { if (done.has(id)) furthest = i; });
  const open = Math.min(levels.length, furthest + lookahead + 2);
  return levels.map((id, i) => ({ id, unlocked: i < open, completed: done.has(id) }));
}

Fixing the unlock check alone was not quite enough. The picker also asked "is this one completed?" and "was it perfect?" per level, each a scan of the save. I benchmarked that in Node with 1,000 levels: 1.8 ms at 23 completed, 13–15 ms at 500 and at 1,000. Fifteen milliseconds is nearly a whole 60 Hz frame, so those went into the same single pass with a Set each.

After both changes in this post, the same Chromium profile of the same action showed 706 ms busy, and the unlock check was gone from the list.

The test that tested nothing

Changing how a game decides which levels are open is not a change I want to get slightly wrong. One level off and a player is either locked out of something they earned or handed something they did not. So the new code got an equivalence test: keep the old per-level version in the test file, generate 3,000 random saves, and require both to agree on every level of every one.

It passed. Then I broke the new code on purpose, deleting one rounding step from the rule, and it still passed.

The random inputs came from a small seeded generator, so a failure would name a seed you could rerun. This one:

// The first version of the test's generator (Park–Miller), seeded 1..3000.
function random(seed) {
  let s = seed;
  return () => (s = (s * 16807) % 2147483647) / 2147483647;
}
const size = Math.floor(random(seed)() * 25);  // how many levels this save has

For a small seed, the first number out of that generator is tiny. Seed 3,000 gives 3,000 × 16,807 / 2,147,483,647 ≈ 0.023, and 0.023 × 25 rounds down to zero. I reran it to be sure: all 3,000 scenarios drew a level list of length zero. The test compared the two implementations on an empty list three thousand times.

The fix was a generator that mixes its seed properly (mulberry32), plus a test that checks the inputs: over the 3,000 draws, more than a thousand must have over ten levels, more than a thousand must have over three completed, and every lookahead value in the pool must appear. Then four deliberate bugs, one at a time: the missing rounding step again, a missing clamp at zero, taking the first completed level instead of the furthest, and dropping the check for a level that is not in the list. Each one failed the suite. The real code went back and the suite was green again.

I have written about checks that pass while broken before, and this is the same lesson from another angle. A randomised test reports how many cases it ran, never how many of them were different from each other.

Cause two: a hundred panels nobody could see

The other cost was in the carousel itself. Home had 3,684 elements, 1,494 images and 108 running animations. One collection is on screen at a time. The other 99 were fully built, each with its framed cover, ribbon, pieces and medal. With 108 animations running, the phone recalculated styles on most frames, and most of what it restyled was off screen.

Before writing any code I tested that idea on the phone, by injecting one CSS rule over the inspector connection and recording the idle timeline again:

.carousel-panel[aria-hidden] { display: none !important; }

Style recalculation dropped from about 13 ms to about 2.7 ms a frame. That was enough to commit to the change.

Every panel keeps its slot on the scrolling strip, so native scroll snapping and the strip's width are untouched. Only the panel showing and the one either side draw anything:

// Simplified. Every panel keeps its place; three of them draw.
const Panel = memo(function Panel({ collection, showing, drawn }) {
  return (
    <section className="carousel-panel"
             aria-hidden={!showing || undefined}
             inert={!showing || undefined}>
      {drawn && <PanelContent collection={collection} />}
    </section>
  );
});

{collections.map((c) => (
  <Panel key={c.index} collection={c}
         showing={c.index === shown}
         drawn={Math.abs(c.index - shown) <= 1} />
))}

The strip already used scroll-snap-stop: always, so one swipe never passes more than one panel, and the panel it lands on is always one that was drawn. memo matters too: when shown changes, only the two to four panels whose flags flip re-render, not all hundred.

I did not measure the "reloading" directly, but the same code explains it. The old code only mounted a panel's ten level buttons once that panel became shown, which flips halfway through a swipe, so the buttons and stars popped in mid-gesture. The cover image also switched between loading="lazy" and "eager" depending on the same flag. Now the neighbours are fully built before they slide in, with inert so they cannot be tapped or focused while off screen.

Proving it looks the same

A performance change to a game screen has to leave every pixel alone, so I compared frozen-frame screenshots of the old and new builds in WebKit and Chromium.

The first attempt was useless. The control, old build against itself, already differed by 50,000 to 377,000 pixels, because the light bursts and sky sparkles are random. Seeding Math.random and pinning the clock in both pages made the control clean. After that, old against new was identical in every scene but one: stepping to the next collection and back showed about 17,000 changed pixels. That turned out to be the glow on the current level, which no longer restarts its cycle when you come back, because the panel was never torn down. That is the fix doing its job.

The numbers, on the iPhone

Before After
Back to home: carousel on screen 157–305 ms 19–22 ms
Back to home: worst frame in the next 0.8 s 124–2,253 ms 91–92 ms
One carousel step, frames in 0.65 s 1–8 37–39 (about 58 fps)
Elements on home 3,684 549
Style recalculation per idle frame ~13 ms ~2.4 ms

All 7,950 of the game's tests passed, and four device scenarios (win a level, progress after a relaunch, the daily gift, settings) passed on the iOS simulator and the Android emulator.

What this did not fix: popups were still slow to open. Their numbers did not move with the element count, and the phone's timeline put their cost in compositing, not in JavaScript. That was a separate problem and took its own investigation.

What I would check first next time

  • Profile on the phone, or slow the laptop down. At full speed on a Mac the unlock check would cost roughly a quarter of that, about half a second, easy to wave away. A 4× CPU slowdown put it at the top of the list.
  • Test with a late-game save. The unlock check was cheap on a fresh save and grew with every level won. I did not measure a 500-level save on the phone, but the loop's shape says it only gets worse.
  • A carousel needs three slides, not a hundred. Keep the slots, draw the visible one and its neighbours, and the neighbours stop looking like they are loading.
  • Check what your random test generated. Then break the code and make sure it notices.

More posts

New writing when there is something worth saying. By email or by RSS, whichever you prefer.