Scrivio Interview library
ScenarioIntermediate8 min read · updated 12 November 2026

An image processing service stores pixels as int[height][width] and is slow when iterating column by column. What would you change?

In Java, int[height][width] is not one block of memory: it is an array of separate row arrays, so walking it column by column jumps from one row object to another and misses the CPU cache on almost every read. The fix is to iterate row by row, with the row in the outer loop, or better, to store the image as one flat int[width * height] indexed with y * width + x. Then we measure both versions with JMH before we call it fixed.

Why this question is asked

Image filters, matrix code and game boards all live on two-dimensional grids, and the way we walk the grid can change the running time by a factor of five or more without changing a single arithmetic operation. Interviewers ask this question because it checks whether we know how Java really lays out a 2D array in memory and whether we think about the CPU cache when code is slow. In this answer, we will recap how int[][] is stored, see why column-by-column traversal is slow, fix it first by swapping the loops and then by flattening the array, look at the memory and GC savings, and finish with how to prove the improvement with JMH.

1A Quick Recap of How int[][] Is Stored

Java has no true two-dimensional arrays. When we write new int[1080][1920], we get an outer array with 1080 slots, and each slot holds a reference to its own int[1920] object. So a full HD image is really 1,081 objects: one outer array of references and 1,080 row arrays, each with its own object header and each allocated wherever the heap had room at that moment.

Inside one row, the ints sit next to each other, 4 bytes apart. Between rows there is no promise at all. Row 0 and row 1 may be neighbours on the heap, or they may be megabytes apart, especially after the garbage collector has moved things around.

The second idea we need is the cache line. The CPU never reads a single int from main memory. It reads a cache line, usually 64 bytes, which holds 16 ints. If the next value we need is in the same line, the read is almost free. If it is somewhere else, the CPU waits for main memory, which costs roughly a hundred times more than a cache hit.

Where pixels live in int[1080][1920]
ObjectHoldsNext to
outer int[][]1080 references to rowsanything
row 0 (int[1920])pixels (0,0) .. (1919,0), 7680 bytesunknown, wherever it was allocated
row 1 (int[1920])pixels (0,1) .. (1919,1), 7680 bytesunknown
row 1079last line of the imageunknown
Pixels inside a row are contiguous. Rows are separate objects with no fixed position relative to each other.

2Why Column-by-Column Traversal Is Slow

Here is the kind of loop the service had. The outer loop runs over x, the inner loop over y, so for each column it visits every row.

Java
int[][] img = new int[1080][1920];
long sum = 0;
for (int x = 0; x < 1920; x++) {
for (int y = 0; y < 1080; y++) {
sum += img[y][x]; // each step: load a new row reference, then one int far away
}
}

Notice what each step of the inner loop does. It loads the reference img[y] from the outer array, follows it to a different row object, and reads one int there. The next step does the same for row y + 1, which lives somewhere else. So every read touches a new cache line, and we use 4 bytes out of the 64 the CPU fetched. By the time we come back to row 0 for column x + 1, its cache line has usually been pushed out by the 1,079 other lines we touched in between.

The hardware prefetcher, the part of the CPU that guesses which memory we need next, cannot help much either, so the loop spends most of its time waiting for memory rather than adding numbers.

3Fix 1: Put the Row in the Outer Loop

The cheapest change is to swap the loops so that the inner loop walks along a row. We can also hoist the row reference out of the inner loop, which makes the intent obvious and saves a load per pixel.

Java
long sum = 0;
for (int y = 0; y < 1080; y++) {
int[] row = img[y]; // one row object
for (int x = 0; x < row.length; x++) {
sum += row[x]; // sequential reads: 16 ints per cache line
}
}

Now the inner loop reads memory in order, so one cache line serves 16 pixels and the prefetcher can stream the next lines before we ask for them. Looping to row.length also lets the JIT compiler prove the index is always in range and drop the bounds check, which in turn makes it easier for C2, the optimising JIT compiler, to vectorise the loop. On a typical machine this kind of change makes the loop several times faster, but the exact factor depends on the image size and the CPU, which is why we measure.

But there is a catch: some algorithms really are column-oriented, such as a vertical blur. For those we can still process the image in tiles, or transpose it once, but the bigger win usually comes from the next fix.

4Fix 2: Store the Image as One Flat Array

Instead of an array of rows, we can keep all pixels in one int[] and calculate the position ourselves. Pixel (x, y) lives at index y * width + x. This is exactly how image formats and libraries such as java.awt.image.BufferedImage store their data internally.

Java
final class Image {
final int width, height;
final int[] px; // one contiguous object
Image(int width, int height) {
this.width = width; this.height = height;
this.px = new int[width * height]; // 1920 * 1080 = 2,073,600 ints
}
int get(int x, int y) { return px[y * width + x]; }
void set(int x, int y, int v) { px[y * width + x] = v; }
}
Image im = new Image(1920, 1080);
im.set(5, 2, 42);
System.out.println(im.px[2 * 1920 + 5]); // 42

Now the whole image is one block of memory. Row-by-row traversal is a single linear scan from index 0 to the end, which is the best case for the cache and the prefetcher. Even a column walk becomes more predictable, because it is a fixed stride of width * 4 bytes, a pattern the prefetcher can follow. And many operations no longer need nested loops at all: brightening every pixel is one loop over px, and copying an image is one System.arraycopy call.

The cost is that we write the index arithmetic ourselves, and a mistake such as x * width + y silently reads the wrong pixel instead of throwing. So we keep the arithmetic inside small methods like get and set, and test them.

5Fewer Objects, Less Work for the GC

The flat array also helps memory. Every Java object has a header, typically 12 to 16 bytes, and every row adds a 4 or 8 byte reference in the outer array. For 1,080 rows that is only around 20 KB, which is small next to 8 MB of pixels, but a service that handles many small tiles, for example 64 by 64 thumbnails, pays the header and reference cost on every row of every tile.

The garbage collector also has less to do. It traces one object instead of 1,081, and a large single array is often placed in a special region for big objects (G1 calls them humongous objects), so it is not copied around on every young collection. Fewer objects means shorter marking and fewer references to update when objects move.

6Proving It With JMH

A change like this should come with numbers. JMH, the Java Microbenchmark Harness, runs the code enough times to let the JIT warm up, prevents the compiler from removing work whose result is unused, and reports a stable average with an error margin. A hand-written loop around System.nanoTime() gets all of these wrong.

Java
@State(Scope.Benchmark)
public class PixelBench {
int[][] grid = new int[1080][1920];
int[] flat = new int[1080 * 1920];
@Benchmark public long columnMajor() { long s = 0; for (int x = 0; x < 1920; x++) for (int y = 0; y < 1080; y++) s += grid[y][x]; return s; }
@Benchmark public long rowMajor() { long s = 0; for (int[] row : grid) for (int v : row) s += v; return s; }
@Benchmark public long flat() { long s = 0; for (int v : flat) s += v; return s; }
}
// Returning s stops the JIT from discarding the loop as dead code.

We run the benchmark on hardware like production, with realistic image sizes, and then confirm with a profiler on the real service that the pixel loop was actually the hot spot. If the service is slow because of decoding or network transfer, faster loops will not show up in the latency at all.

7Follow-up questions

Would using Integer[][] instead of int[][] make it worse?

Much worse. An Integer[][] row holds references to separate Integer objects, so even a row-by-row walk follows a pointer for each pixel, and each pixel costs about 16 bytes of object instead of 4 bytes of int. For pixel data we always use primitive arrays.

Is y * width + x safe from overflow?

For normal images, yes: 1920 * 1080 is about two million, far below Integer.MAX_VALUE. A single Java array is limited to about 2.1 billion elements anyway. For very large grids we compute the index as a long, or use Math.multiplyExact to fail loudly, and we validate width and height when the image is created.

Does the JIT fix the loop order for us?

No. HotSpot does not interchange nested loops, because it cannot prove that reordering is safe and beneficial in general. We have to write the loops in the order that matches the memory layout.

8Conclusion

In this answer, we saw that int[height][width] in Java is an array of separate row objects, so a column-by-column walk jumps between objects and wastes most of every cache line. Swapping the loops so the row is outer turns that into sequential reads, and storing the image as one flat int[] indexed with y * width + x gives a single contiguous object with fewer headers and less GC work. We keep the index arithmetic inside small methods, and we prove the gain with JMH and a profiler rather than assuming it.

What to say in the interviewAbout 90 seconds aloud

Open with

The key fact is that Java does not have real 2D arrays. int[height][width] is an outer array of references, and each row is its own int[] object somewhere on the heap.

Then, if they want more

When the service walks column by column, every read goes to a different row object, so it pulls in a 64-byte cache line, uses 4 bytes of it, and has usually lost that line by the time it comes back for the next column. The loop ends up waiting on memory.

The first change I would make is to swap the loops so the outer loop is over rows and the inner loop walks along one row, ideally hoisting int[] row = img[y] so the JIT can drop bounds checks and vectorise.

The better long-term change is to store pixels in one flat int[width * height] and index with y * width + x, behind small get and set methods so nobody writes the arithmetic by hand.

That gives one contiguous object, so scans are linear, copies are a single arraycopy, and the GC traces one object instead of a thousand row objects with their headers. Before and after, I would measure with a JMH benchmark using realistic image sizes, and check with a profiler that this loop really is where the time goes in the service.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "An image processing service stores pixels as int[height][width] and is slow when...": https://scrivio-interview-library.netlify.app/java/arrays/bf55e9854a/