Bound Thumbnail Decoding Before Adding Another Image Cache
A thumbnail grid looks cheap because each cell is small. Then twenty cells appear together, twenty image decodes start, and memory jumps before the cache contains its first useful result.
A cache limit does not limit work already in progress. The decoding stage needs its own budget.
Our PhotosPicker article covers importing and downsampling one selected image. Let’s focus on what changes when many visible cells request thumbnails together.
Start with one shared decoder
A dedicated actor is a simple baseline for serializing synchronous Image I/O work. Create one instance for the image-loading feature, not one instance per row.
import CoreGraphics
import Foundation
import ImageIO
actor ThumbnailDecoder {
enum Failure: Error { case invalidSize, unreadable, decodeFailed }
func decode(file: URL, pointWidth: Double, pointHeight: Double, scale: Double) throws -> CGImage
{
try Task.checkCancellation()
let pixels = max(pointWidth, pointHeight) * scale
guard pointWidth > 0, pointHeight > 0, scale > 0,
pixels.isFinite, pixels <= 4096
else { throw Failure.invalidSize }
let sourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary
guard let source = CGImageSourceCreateWithURL(file as CFURL, sourceOptions) else {
throw Failure.unreadable
}
let options: CFDictionary =
[
kCGImageSourceCreateThumbnailFromImageAlways: true,
kCGImageSourceCreateThumbnailWithTransform: true,
kCGImageSourceThumbnailMaxPixelSize: Int(ceil(pixels)),
kCGImageSourceShouldCacheImmediately: true,
] as CFDictionary
guard let image = CGImageSourceCreateThumbnailAtIndex(source, 0, options) else {
throw Failure.decodeFailed
}
try Task.checkCancellation()
return image
}
}
The actor-isolated method contains no suspension point. One call finishes its synchronous decode before another call on this actor starts decoding. Callers await the actor from outside; they do not run the decode on the main actor merely because a SwiftUI task requested it.
Do not add Task.detached inside the method and immediately release the actor to handle another request. That would change the concurrency policy you just established. If profiling shows one decoder cannot keep up, use a small measured worker pool with an explicit maximum rather than a task for every item in the library.
Budget pixels, not points or compressed bytes
A 120-point image on a 3x display needs a different pixel budget from the same view on a 2x display. The helper multiplies the larger point dimension by scale and rounds up.
Image I/O’s thumbnail size and transform options bound the longest pixel dimension and account for source orientation. The 4,096-pixel ceiling is this loader’s chosen limit, not an Image I/O requirement. Use a limit appropriate to the feature.
This is a fit-inside thumbnail. If your view crops to fill a wide or tall rectangle, calculate the decode dimensions from that crop requirement or accept that the visible crop may be softer. A single longest-edge rule does not automatically produce every aspect-fill target at full display resolution.
Compressed file size is a poor proxy for decoded memory. For a returned CGImage, bytesPerRow * height describes its pixel-row storage more closely, but still excludes decoder workspace, caches, and rendering resources. A tiny compressed image can expand into a large bitmap.
Keep cancellation useful without promising interruption
The checks before and after decoding have different jobs. The first lets an already-cancelled request leave before starting expensive work. The second stops a completed but unwanted image from becoming a successful result.
Neither check interrupts the synchronous decoder halfway through its work. Cancel requests for offscreen cells promptly, and avoid filling the actor’s queue with thousands of speculative requests. Serial decoding bounds simultaneous decode work; it does not itself bound queued tasks or images retained by callers.
Use the row’s current item identity before publishing a result, just as in our stale search-result example. A cell recycled for another asset should not accept the previous asset’s thumbnail just because its decode eventually finished.
Add caching after the pipeline is controlled
A cache key should include the asset’s stable identity and revision, requested pixel bucket, and any rendering choices that change the result. A URL alone can name changed content, and a 120-pixel thumbnail is not interchangeable with a 600-pixel request.
Count retained decoded cost separately from in-flight decoding. Evicting cache entries cannot release an image still held by several views. Likewise, setting a cache cost limit is not evidence that the whole process stays below that number.
Profile a cold scroll, a repeated scroll, and a rapid reversal through the grid. Track decode count, cancelled requests, retained thumbnail cost, and process peak memory. The cold path exposes concurrency; the warm path tells you whether the cache is useful.
September 2026 review: the Swift 6.4 actor compiled and decoded a fixture into a 240×135 thumbnail for a 120-point, 2x request. Assertions covered the pixel bound, invalid dimensions, and an unreadable source. Device memory, throughput, orientation fixtures, and cancellation during a real scroll remain measurements for the app.