skip to content

In a mobile art-museum app, why do small artwork JPEGs in a grid crash older phones with out-of-memory, and what fixes it?

level: juniorimportance: must knowfreq 58%

answer

  1. what the decoder actually allocates
  2. width x height x bytes per pixel
  3. read the dimensions before the pixels
  4. decode to the view's pixels, not the file's
  5. decode off the UI thread

basics

~20 s

Memory follows pixels, not file size: a 4000 x 3000 photo decodes to about 48 MB at four bytes a pixel, however small the JPEG. Read the dimensions first; decode downsampled to the cell's pixels, off the UI thread.

solid answer

~50 s

A JPEG is compressed; to draw it, the decoder expands it into a pixel buffer of `width x height x bytes per pixel`. At the common four bytes a pixel, a 4000 x 3000 artwork photo needs about 48 MB however small its file, so fifteen visible cells decoded whole ask for roughly 720 MB and an older phone's per-app memory limit ends the app. The fix lives in the decode step: read the width and height from the file's header without allocating pixels, work out the cell's size in pixels (its layout size times the screen density), and ask the decoder for a subsampled image near that size - about 360 x 360 pixels, roughly 0.5 MB. Decode off the UI thread and cache the result at that size. Asking the server for a smaller variant helps as well, but the decode rule must hold whatever bytes arrive.

code

pseudocode · 8 lines
pseudocode
function decodeForView(file, viewWidthUnits, viewHeightUnits, density):
  header = readHeader(file)              # width and height only, no pixels
  targetW = viewWidthUnits * density
  targetH = viewHeightUnits * density
  factor = 1
  while header.width / (factor * 2) >= targetW and header.height / (factor * 2) >= targetH:
    factor = factor * 2
  return decodeSubsampled(file, factor)  # e.g. 4000 x 3000 with a 360 target -> 500 x 375

go deeper

for a junior

Remember the formula: width times height times four bytes. Say that a small file can still be a huge decoded image, and that the fix is decoding to the view's pixel size.

for a middle

Explain the steps: read the header without pixels, convert the view's layout size to pixels with the screen density, subsample during decode, and decode on a background thread.

for a senior

Do the arithmetic for a full screen of cells against an older phone's budget, point out that the peak allocation is what ends the app, and treat the decode as the guard even when the server sends variants.

for a principal

Frame it as a team rule: no decode larger than its view, enforced by a debug check and by peak-memory tests on the oldest supported phone, so every new surface inherits the guard.

## Why the file size misleads A JPEG, PNG, WebP or HEIC file is **compressed**: it stores a recipe for the picture, not the picture. Before anything can be drawn, the platform's image decoder expands that recipe into a **decoded image** - a buffer holding every pixel's colour. Its size depends only on the pixel dimensions and the pixel format: `decoded bytes = width x height x bytes per pixel` The common pixel format stores red, green, blue and alpha at one byte each, so **four bytes per pixel**. A 4000 x 3000 photograph is 12 million pixels, about **48 MB** decoded - whether its file weighs 300 KB or 6 MB. One platform's own guidance gives the same arithmetic: a 2048 x 1536 image takes about 12 MB decoded whole and about 0.75 MB when subsampled to roughly 512 x 384. ## The arithmetic for the museum grid Assume a three-column grid on a phone about 1,080 pixels wide, so each cell is about 360 x 360 pixels, and about fifteen cells on screen (both are this scenario's assumptions). | Decode choice | Pixels per image | Memory per image | Fifteen visible cells | |---|---|---|---| | Full 4000 x 3000 decode | 12,000,000 | ~48 MB | ~720 MB | | Power-of-two subsample to 500 x 375 | 187,500 | ~0.75 MB | ~11 MB | | Exact 360 x 360 target | 129,600 | ~0.52 MB | ~7.8 MB | The first row explains the crash. Every app has a memory limit that depends on the device; when the app passes it, the system ends the app, and an older phone's limit is far below 720 MB. Scrolling makes it worse: cells off screen may still hold their decodes in the memory cache, and several decodes can be in flight at once. ## Decode to the view, not the file The fix is to make the decode itself produce a small image, so the full-size buffer never exists: 1. **Read the header first.** Image formats record width and height near the start of the file, and decoders can report them without allocating the pixel buffer. 2. **Compute the target in pixels.** Take the view's layout size and multiply by the screen's density: a 120-unit cell on a 3x screen needs 360 pixels, not 120. 3. **Ask for a subsampled decode.** Many decoders shrink by power-of-two steps while decoding. Choosing the largest step that keeps both sides at or above the target, a 4000 x 3000 file with a 360-pixel target comes out at 500 x 375 - a little larger than the cell rather than smaller, which keeps it sharp. 4. **Decode off the UI thread.** Decoding is CPU-heavy work; on the UI thread it stalls scrolling. Hand the result back to the UI thread only to display it. 5. **Cache at the decoded size.** The memory cache stores the 0.75 MB result, keyed by the image's URL and the target size, so a second visit does not repeat the decode. ## What downsampling after the fact does not fix - **Scaling in the view changes only the drawing.** A view set to scale-to-fit still holds the full 48 MB buffer behind it. - **Decoding full size, then resizing, still peaks at 48 MB.** The peak allocation is what ends the app, and two or three such decodes in parallel are enough on an older phone. - **A bigger memory cache makes it worse.** It keeps more oversized buffers alive; the cure is smaller entries, not more room. - **Trusting the server is not a guard.** A smaller server variant reduces download size and decode time, but a wrong URL, an old cached response or a user-shared original can still arrive full size. ## Where this sits in the design Decoding to the view's size is the first rule of a client image pipeline, and interviewers use it to check whether a candidate thinks in pixels or in files. It pairs with two neighbouring decisions that belong elsewhere: which image sizes and formats the server offers and how the client asks for them, and how a scrolling list decides which rows to prepare ahead of the viewport. Whatever those decide, the decode step is the last line of defence: - **It reads the dimensions** before committing any memory. - **It refuses to build a buffer larger than the view needs**, in pixels, at the current density. - **It keeps the expensive work off the thread that draws the screen.** - **It caches what it produced**, at the size it produced it. A useful habit in a design round is to state the arithmetic out loud - pixels, times four, times the number of images alive at once - and compare it with a stated memory budget for the oldest supported phone. The number usually makes the argument for you.

  • Why not decode each artwork at full size once and keep only a scaled-down copy?
    Because the full decode still allocates the 48 MB buffer before the copy exists. Peak memory, not steady-state memory, is what ends the app, and with two or three decodes running in parallel an older phone passes its limit during the resize. Subsampling inside the decode means the large buffer never exists, and it also saves the CPU time of producing pixels that are thrown away.
  • The visitor rotates to landscape and the grid cells grow; what happens to the cached decodes?
    The memory cache is keyed by URL and target size, so a larger cell is a new key and needs a new decode. The bytes are still in the disk cache, so no download is repeated, only the decode. A pipeline may choose to reuse an entry within a small size tolerance to avoid churn, but it should not serve a much smaller decode to a much larger cell, which looks blurry.
  • How would you catch an oversized decode before a release ships?
    In debug builds, compare each decoded image's pixel size with its view's pixel size and log or flag any image more than an agreed factor larger - twice the view is a reasonable threshold to start from, as an assumption. Then measure peak memory while scrolling the grid on the oldest phone you support, because that device's limit is the one that matters.

  • A 300 KB JPEG costs about 300 KB of memory once it is on screen.
  • Setting the view to scale-to-fit shrinks the decoded image's memory.
  • The client can decode whatever arrives, because sizing images is the server's job.
  • Decoding on the UI thread is fine because the image files are small.
  • An out-of-memory crash in an image grid means the memory cache should be larger.