Engineering

RAW Photo Culling on iOS: Taming Memory at Scale

Lazy grids, ImageIO downsampling, and NSCache sizing lessons from prototyping a SwiftUI companion app for RAW photo culling.

· · 8 min read
Close-up of a hand scrolling through a dense grid of small photo thumbnails on a tablet screen

TL;DR: A SwiftUI RAW photo culling grid stays fast and crash-free at thousands of images when four things hold together: the grid is built with LazyVGrid so only visible cells exist, every thumbnail is decoded small with ImageIO instead of at full resolution, in-flight PHCachingImageManager requests get cancelled as the user scrolls past them, and the thumbnail cache has a deliberately sized memory ceiling via NSCache. Skip any one of the four and the app degrades, usually during the fast, continuous scroll a culling session is built around.

We build desktop batch-processing and duplicate-detection tools for photographers, and over the past few months we've been prototyping a SwiftUI companion app that lets a photographer triage a shoot, scroll through thousands of RAW-derived thumbnails and mark keepers, without being at the desktop machine. The first build worked fine against a test library of a few hundred images and started dropping frames almost immediately once we pointed it at a real import: a wedding or sports shoot that routinely runs past several thousand RAW frames. That gap between a demo library and a real one is where everything below came from.

When the complexity creeps past what a two-person photo-software team can own in spare time, this is exactly the kind of problem we'd hand to YuSMP Group's iOS engineering team rather than carrying it alone, since the failure modes here are narrow but easy to miss until a real library exposes them.

Why iOS Photo Grids Fall Over at Scale

A scrolling grid of thumbnails looks like a layout problem, rows and columns of small images, but it's really a memory and scheduling problem wearing a layout's clothes. Every thumbnail that gets drawn also has to be decoded somewhere, and every decode allocates a bitmap that has to live in memory until something evicts it. At a few hundred images none of this matters; the whole working set fits comfortably and the system never has to make hard choices. At a few thousand, three things start competing for the same memory and the same frame budget at once: the cells currently on screen, the thumbnails already decoded from a moment ago, and the new ones that need to decode as the user keeps scrolling. The scenario that exposes this isn't a demo with a hundred curated photos, it's a photographer dumping a real card onto the device and scrolling through the whole import in one pass, which is the actual use case a culling tool exists for.

LazyVGrid, View Recycling, and What SwiftUI Actually Keeps Alive

The first mistake in our prototype was building the grid from a plain VStack of rows backed by a ForEach over the entire photo array. SwiftUI evaluates that view hierarchy eagerly enough that every thumbnail's image loading got kicked off up front, whether or not the cell was anywhere near the viewport. LazyVGrid (and its horizontal counterpart LazyHGrid) fix this by only instantiating the views for rows near the visible scroll position, plus a small surrounding window SwiftUI manages internally. It's worth being precise about what "lazy" means here: SwiftUI isn't reusing a fixed pool of recycled cell objects the way UICollectionView does with reusable cells; it's deferring creation of each cell's view (and the image load behind it) until that cell is actually needed, then tearing the view down again once it scrolls far enough out of range. For a culling grid, swapping the container was a small change that took scrolling from visibly stuttering on load to smooth, and it's the baseline everything else in this piece assumes is already in place.

Downsampling Before Display: ImageIO and CGImageSource

Fixing the grid container got scrolling smooth initially, but memory climbed the longer a session ran, and the app eventually took a memory-pressure kill on a mid-range test device. The cause was the same one that trips up most first attempts: our source thumbnails were RAW-derived JPEGs several thousand pixels wide, and we were handing a plain UIImage loaded from that full-size file straight to a SwiftUI Image view sized for a roughly 100-point grid cell. SwiftUI's Image resizes what it displays independent of what it decodes; a multi-megapixel source decoded at full resolution and then squeezed visually into a tiny cell still allocates the full-resolution bitmap in memory before a single pixel is drawn.

Why a Full-Resolution Decode Costs Memory Even in a Tiny Cell

A decoded bitmap's memory footprint is roughly width × height × 4 bytes for RGBA, independent of how large the view displaying it happens to be. A 4000×3000 JPEG decodes to tens of megabytes in memory regardless of whether it's shown at full width or at 100 points. Multiply that by a few hundred thumbnails in flight during a fast scroll and you're well past the point where the system steps in. The fix is ImageIO's thumbnail-generation APIs: CGImageSourceCreateThumbnailAtIndex, called with options including kCGImageSourceThumbnailMaxPixelSize set to the grid cell's actual pixel size, decodes the source at that target size directly rather than decoding in full and resizing afterward. A thumbnail generated this way for a roughly 100-point cell at the device's screen scale costs a small fraction of a full-resolution decode, often a reduction of an order of magnitude or more for a typical culling grid's cell size.

PHCachingImageManager and Cancelling In-Flight Requests

Where the thumbnails come from matters too. When the companion app reads from the user's system photo library rather than a private import folder, the natural API is Photos framework's PHCachingImageManager, which layers an internal cache and request-coalescing on top of the raw asset-fetching APIs. Its request-and-cancel model is the piece that's easy to get wrong in a fast-scrolling grid: each visible cell issues an image request, and if the user scrolls quickly, dozens of requests for cells that are no longer visible can still be in flight, each one decoding a thumbnail nobody will ever see. PHCachingImageManager exposes startCachingImages and stopCachingImages calls specifically so a grid can tell it which assets are about to become visible and which have scrolled out of range, and cancelling requests for cells that have left the viewport (rather than letting them complete and get discarded) is what keeps the decode queue from falling behind during a fast flick through a shoot.

Bounding Memory With NSCache

Lazy building, right-sized decoding, and proper request cancellation solve the immediate crash and the jank, but a culling session is a long scroll in both directions. A photographer moves forward through a shoot, then scrolls back to compare a borderline shot against ones already passed, which means recently-seen thumbnails should stay available rather than re-decoding on every pass, a caching problem distinct from the decode-size problem above. We hold decoded thumbnails in an NSCache keyed by asset identifier, and the detail that matters is setting totalCostLimit deliberately rather than leaving the cache unbounded. NSCache does evict automatically under system memory pressure even with no limit set, but an unbounded cache on a long culling session will still grow far larger than it needs to before that pressure response kicks in, and the eviction itself becomes a disruptive stall rather than a quiet background process. We pass the decoded byte size of each thumbnail (width × height × 4, the same arithmetic as above) as the cost argument when inserting it, so totalCostLimit maps directly to a real memory budget rather than an arbitrary item count that doesn't account for varying thumbnail sizes.

Avoiding Scroll Jank and Thermal Throttling

A culling workflow is scrolled fast and continuously; photographers flick through a shoot looking for standouts rather than reading each thumbnail carefully, and that fast, sustained scrolling is exactly the condition that exposes any remaining slack in the pipeline. The two culprits we kept running into were decode work that landed on the main thread instead of a background queue, specifically a thumbnail-overlay compositing step we'd bolted on for selection badges that wasn't dispatched off the UI thread the way the core ImageIO decode already was, and devices hitting an elevated thermal state during a long, continuous culling session, which iOS responds to by throttling CPU and GPU performance system-wide. ProcessInfo.thermalState is worth observing directly rather than inferring from dropped frames alone: at .serious or .critical, it's reasonable for the app to reduce decode concurrency or temporarily widen the cache's eviction window, rather than keep pushing the same workload into a device that's already throttling itself. Moving overlay compositing off the main thread and watching thermal state directly removed the remaining stutter on top of the gains from lazy grid building, downsampled decoding, and bounded caching.

What We'd Do Differently Next Time: Pre-Ship Checklist

If we were starting this companion-app grid over today, we'd set the ImageIO downsample target and the NSCache cost limit from the very first prototype instead of treating them as a performance pass to bolt on later, because by the time we hit the memory crash the grid, the selection overlay, and the caching-request logic were all already built around full-resolution assumptions, and untangling that afterward took longer than designing it correctly from the start would have. Before shipping a screen like this, we check:

  • Confirm the grid uses LazyVGrid, not an eagerly-evaluated VStack/ForEach over the full photo array, so cells are only built near the viewport.
  • Decode thumbnails with CGImageSourceCreateThumbnailAtIndex and kCGImageSourceThumbnailMaxPixelSize set to the actual grid cell size, never the source resolution.
  • Call stopCachingImages on PHCachingImageManager requests for cells that have scrolled out of the viewport, not just startCachingImages for ones coming into view.
  • Set NSCache.totalCostLimit deliberately using the decoded byte size of each thumbnail as cost, rather than leaving the cache unbounded or sized by item count alone.
  • Test against a realistic library size, not a few hundred curated images. The failure modes above mostly don't surface until a real import lands on the device.
  • Profile fast, continuous scrolling specifically, and watch ProcessInfo.thermalState during a long session, since jank and throttling both show up during rapid culling gestures rather than slow browsing.

Frequently Asked Questions

How many RAW-derived thumbnails can a SwiftUI LazyVGrid handle before it drops frames?

With LazyVGrid and thumbnails downsampled through ImageIO instead of full-resolution decodes, we've kept scrolling smooth well past several thousand RAW-derived thumbnails, because only the cells near the visible viewport are ever instantiated or decoded. Feed the same grid full-size JPEG derivatives without downsampling first, and frame drops start in the low hundreds, since every visible cell now has to decode a multi-megabyte image before it can draw a few dozen pixels of it.

Does resizing a SwiftUI Image view reduce memory, or just the display size?

Just the display size, by default. A plain SwiftUI Image loaded from a UIImage decodes at the source's native pixel dimensions regardless of the frame you resize it to, so a 4000-pixel-wide RAW thumbnail squeezed into a 100-point grid cell still allocates a full-resolution bitmap in memory before it's drawn. Reducing memory requires decoding at a smaller size up front, with ImageIO's thumbnail APIs, not resizing the already-decoded image after the fact.

Should thumbnails be generated ahead of time, or downsampled on the fly with ImageIO?

Both, for different reasons. Pre-generating thumbnails during import avoids repeating the same downsample work every time a cell scrolls back into view, while CGImageSourceCreateThumbnailAtIndex handles the on-the-fly case, a photo that hasn't been pre-processed yet or a size the pre-generated cache doesn't cover. Relying on on-the-fly downsampling alone against RAW-derived sources still pays a real decode cost per cell during fast scrolling.

What causes jank specifically during fast scrolling through a photo grid on iOS?

The two recurring causes are synchronous image decode work landing on the main thread as cells scroll into view, and PHCachingImageManager requests that were started for cells the user has already scrolled past but were never cancelled. Both show up specifically during fast, continuous scrolling rather than a slow browse, because fast scrolling asks the decoder and the caching manager to keep up with a much higher rate of newly visible cells.

Is LazyVGrid enough, or do I need a UICollectionView via UIViewRepresentable?

For a uniform grid of fixed-size cells, LazyVGrid's built-in lazy instantiation is enough on its own. A UICollectionView wrapped in UIViewRepresentable earns its place when you need prefetching APIs with finer control, variable cell sizes, or section-level diffing that LazyVGrid doesn't expose directly, trade-offs worth weighing against the added bridging complexity before reaching for it by default.

How do I bound memory with NSCache for a large local photo library?

Set totalCostLimit on the NSCache instance to a byte budget your target devices can actually spare, typically in the tens of megabytes for a thumbnail cache sized for the downsampled images, and pass the decoded byte size of each thumbnail as the cost when inserting it. NSCache evicts automatically under memory pressure even without a limit, but setting one deliberately keeps the cache from growing to the point where eviction itself becomes disruptive during a long culling session.

Does this apply the same way on iPad or Mac Catalyst as on iPhone?

The mechanics are identical, but the available budget shifts: iPad and Mac Catalyst builds typically have more RAM to spend on NSCache limits and can afford larger downsample targets for sharper thumbnails on bigger, higher-density screens, while iPhone targets need tighter limits to avoid memory pressure on a smaller shared budget. A companion app built for both should size these parameters per device class rather than sharing one constant.

For the current parameters and defaults referenced throughout this piece, Apple's ImageIO CGImageSource documentation covers the thumbnail-generation options in detail.

See a desktop-grade engine in actionPhotoTile runs its full batch pipeline natively, no external capacity required.
About the program