Top 3 Worst 3D Array Access Patterns for Cache
Accessing a 3D array in an order that frequently jumps across memory, rather than sequentially, leads to severe cache thrashing. The worst patterns include iterating through the outermost dimension first (e.g., `array[z][y][x]` accessing `x` in the innermost loop for C-order arrays) or striding large distances, which causes new cache lines to be fetched for almost every element, evicting previously useful data.
The top 3
- Opposite-Order 3D Traversal: Accessing a 3D array in an order that conflicts with its memory layout, such as iterating column-major (e.g., `for x, for y, for z`) on a row-major C-style array `arr[z][y][x]`, causes a cache miss for almost every element as memory addresses are non-contiguous.
- Hyper-Strided Non-Contiguous Jumps: When accessing elements with large, non-unit strides across multiple dimensions simultaneously (e.g., `arr[i*S1][j*S2][k*S3]` where S1, S2, S3 are large), the pattern resembles a sparse sampling of the 3D space, leading to very poor spatial and temporal cache locality.
- Innermost Loop Non-Unit Strides: Even when following the correct memory layout order, if the innermost loop iterates with a stride greater than one (e.g., `arr[z][y][x += k]` where `k > 1`), it bypasses contiguous elements within a cache line, wasting fetched data and increasing cache misses.
Sources
Open the full topic