42.1 Arrays and Memory Layout

Matrix layout influences performance through cache locality and stride. Java arrays are row‑major when you use float[][] or double[][], but a single flat array often performs best.


42.1.1 Flat Row‑Major Storage

// MxN row-major matrix stored in one array
class Mat {
  final int M, N;
  final float[] a; // size M*N
  Mat(int M, int N) { this.M = M; this.N = N; this.a = new float[M*N]; }
  float get(int i, int j) { return a[i*N + j]; }
  void set(int i, int j, float v) { a[i*N + j] = v; }
}

Row‑major favors iterating j fastest inside the loop when computing across rows.


42.1.2 Column‑Major Access Patterns

If you frequently access columns, consider transposing or storing a transposed copy:

float getCol(float[] a, int M, int N, int j, int i) { // A^T
  return a[j*M + i];
}

Transposition trades memory/time to improve locality for column operations.


42.1.3 Stride and Cache Lines

  • Favor contiguous access along the innermost loop
  • Avoid large strides that skip cache lines
  • Consider blocking (tiling) to keep working sets in cache