Quick revision
The short answer
A Java int[4096][4096] is an array of 4,096 separate row arrays, each a contiguous 16 KB block. Summing row by row reads memory sequentially, so every 64-byte cache line delivers 16 ints and the hardware prefetcher keeps the next lines coming. Summing column by column jumps to a different row array on every access, touching a new cache line and often a new memory page each time, so most accesses miss the cache and stress the TLB; the JIT also optimises the sequential loop much better.
What to remember
In this answer, we saw that a Java int[4096][4096] is an array of separate 16 KB row arrays, so row-wise iteration reads contiguous memory where each cache line serves 16 ints and the prefetcher runs ahead. Column-wise iteration jumps 16 KB or more on each access, missing the cache and the TLB on nearly every step, and it also defeats bounds-check elimination and vectorisation. The cure is to design access to follow the memory layout: reorder loops, transpose, or flatten the data into a single array in the order the algorithm needs.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
A Java int[4096][4096] is an array of 4,096 separate row arrays, each a contiguous 16 KB block. Summing row by row reads memory sequentially, so every 64-byte cache line delivers 16 ints and the hardware prefetcher keeps the next lines coming. Summing column by column jumps to a different row array on every access, touching a new cache line and often a new memory page each time, so most accesses miss the cache and stress the TLB; the JIT also optimises the sequential loop much better.
Why this question is asked
This is the classic demonstration that the order of two nested loops can change performance by an order of magnitude while the result stays identical. Interviewers like it because it checks whether we know how Java lays out multidimensional arrays and how CPU caches reward sequential access. In this answer, we will look at the memory layout of a Java 2D array, compare the two loops, explain the cache, prefetcher and TLB effects, look at what the JIT does differently, and finish with how to design data access to follow memory layout.
1How Java Lays Out a 2D Array
Java does not have true two-dimensional arrays. An int[4096][4096] is an outer array of 4,096 references, each pointing to a separate int[4096] row. Each row is one contiguous object of 4,096 x 4 bytes, which is 16 KB, plus a small header. The rows themselves are separate objects, usually allocated one after another, but nothing guarantees they are adjacent. The whole structure holds 64 MB of ints, far more than any CPU cache.
| Object | Contents | Size |
|---|---|---|
| outer int[][] | 4,096 references to rows | about 16 KB |
| row 0 | grid[0][0] .. grid[0][4095], contiguous | 16 KB |
| row 1 | grid[1][0] .. grid[1][4095], contiguous | 16 KB |
| ... | one object per row | 16 KB each |
| row 4095 | grid[4095][0] .. grid[4095][4095] | 16 KB |
2The Two Loops
Both methods add up the same 16.7 million ints. The only difference is which index changes in the inner loop.
In sumRows, consecutive accesses are 4 bytes apart. In sumCols, consecutive accesses are in different row objects, at least 16 KB apart. That distance is the whole story.
3Why Row Order Is Fast: Cache Lines and Prefetching
The CPU never loads a single int from memory. It loads the whole 64-byte cache line containing it, which holds 16 ints. In sumRows, the first access to a line may miss, and the next 15 accesses hit, so at most one access in 16 waits for memory.
Better still, the CPU's hardware prefetcher detects that we are reading addresses in increasing order and starts fetching the following lines before we reach them. By the time the loop needs the next line, it is often already in the cache. So the loop runs close to the speed of arithmetic, limited mostly by memory bandwidth.
4Why Column Order Is Slow: A Miss on Nearly Every Access
In sumCols, each step of the inner loop goes to the next row, a different object 16 KB or more away. So each access touches a different cache line, and it uses only 4 bytes of the 64 it loaded. Reading one column pulls 4,096 distinct lines, 256 KB of cache traffic, to use 16 KB of data.
Could the lines stay cached until the next column needs them? The next column needs the very same lines, just 4 bytes further along. But 4,096 lines exceed the first-level cache many times over, and they map onto a limited number of cache sets because their addresses are spaced by a power of two, which makes conflicts likely. So by the time we come back, many lines have been evicted and must be fetched again.
There is also address translation. The CPU translates virtual addresses to physical ones with the help of the TLB, a small cache of page mappings. With 4 KB pages, each 16 KB row spans four pages, so walking down a column touches a new page on every access, 4,096 pages per column, far more than the TLB holds. Each TLB miss adds a page table walk on top of the cache miss. The prefetcher can sometimes follow a constant stride, but the stride here is large and crosses pages, so it helps much less.
- Load g[i]fetch the row reference from the outer array
- Check the rownull check and bounds check on j
- Is the page mapping in the TLB?YesTranslate the addressNoWalk the page table first
- Is the cache line for g[i][j] cached?YesRead 4 bytesNoWait for memory, about 100 ns
- Move to row i + 116 KB or more away: repeat everything
5 steps in order. Play them, or step through them one at a time.
In row order, almost every step takes the fast branch of both decisions.
5What the JIT Does Differently
The JIT compiler also has an easier job with the sequential loop. In sumRows, the row reference is loaded once per row, the bounds check can be proved safe and removed for the whole inner loop, and the loop can be unrolled and vectorised with SIMD instructions that add several ints at once.
In sumCols, the inner loop loads a different row reference every iteration, so it must check that reference for null and check j against that row's length each time, because in Java every row may have a different length. Those checks are cheap compared with the cache misses, but they also stop vectorisation, so the loop cannot use the wide instructions the row version uses.
6Designing Access to Follow Layout
The rule is to make the inner loop walk memory in the order it is stored. When an algorithm genuinely needs column access, for example in matrix multiplication or image processing, we have options. We can reorder the loops so the inner loop is along rows, as matrix multiplication does with the i, k, j ordering. We can transpose the data once and then read the transposed copy row-wise. Or we can store the matrix in a single flat array, which also removes the per-row objects and checks.
With a flat array we choose the layout explicitly, row-major or column-major, to match the dominant access pattern. Tiling, processing the matrix in small blocks that fit in the cache, is the next step for algorithms that need both directions.
7Follow-up questions
Would the difference be smaller for a small array?
Yes. If the whole array fits in the CPU cache, for example int[64][64] at 16 KB, both loops find their data in the cache after the first pass and the gap almost disappears. The effect grows with the data size, which is why it shows so clearly at 64 MB.
Does this apply to collections like List<List<Integer>>?
Even more so. Each Integer is a separate object, so even row-wise iteration chases references, and column-wise iteration is worse. Primitive arrays keep the data contiguous, which is a large part of why they are so much faster for numeric work.
How would you measure this properly?
With JMH, so the JIT is warmed up and dead-code elimination does not remove the loops, using a fork per measurement and returning the sum. On Linux, perf stat or async-profiler with cache-miss events confirms that the column version has many times more cache and TLB misses.
8Conclusion
In this answer, we saw that a Java int[4096][4096] is an array of separate 16 KB row arrays, so row-wise iteration reads contiguous memory where each cache line serves 16 ints and the prefetcher runs ahead. Column-wise iteration jumps 16 KB or more on each access, missing the cache and the TLB on nearly every step, and it also defeats bounds-check elimination and vectorisation. The cure is to design access to follow the memory layout: reorder loops, transpose, or flatten the data into a single array in the order the algorithm needs.
Open with
The reason is memory layout. In Java, an int 4096 by 4096 array is an array of 4,096 separate row arrays, and each row is a contiguous 16 KB block.
Then, if they want more
When I sum row by row, the inner loop reads consecutive ints, so each 64-byte cache line gives me 16 values and the hardware prefetcher sees the sequential pattern and loads the next lines ahead of time. So at most one access in sixteen waits for memory, and usually not even that.
When I sum column by column, every step of the inner loop goes to a different row, 16 KB or more away. Each access touches a new cache line and uses only 4 bytes of it, and with 4,096 rows the lines do not survive in the cache until the next column needs them.
Each step also lands on a different memory page, so the TLB, which caches address translations, keeps missing too. On top of that, the JIT handles the row loop much better: it loads the row once, eliminates bounds checks and can vectorise, while the column loop reloads and checks a different row every iteration.
The design lesson is to make inner loops follow the memory layout. If an algorithm needs column access, I would reorder the loops, transpose the data, or store it in one flat array in the layout the algorithm needs.
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 "Summing an int[4096][4096] row by row takes 20 ms, but summing it column by column takes...": https://scrivio-interview-library.netlify.app/java/java-performance/ae93b7facc/