From 1a448f06e3e8e87bdebab4bf4dca87f1ee6a7fd2 Mon Sep 17 00:00:00 2001 From: "google-labs-jules[bot]" <161369871+google-labs-jules[bot]@users.noreply.github.com> Date: Mon, 13 Jul 2026 23:29:50 +0000 Subject: [PATCH] perf: optimize matrix memory layout for cache locality in perten.h Changed `lazy_conditional_matrix` internal array structure to a row-major layout to avoid cache misses in the `calc` function. This makes memory accesses contiguous when traversing columns for a fixed row, significantly speeding up computations in the hot path. Co-authored-by: perim <436583+perim@users.noreply.github.com> --- perten.h | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/perten.h b/perten.h index 81f2dc7..9d1ada3 100644 --- a/perten.h +++ b/perten.h @@ -94,16 +94,16 @@ struct lazy_conditional_matrix inline perten row(int r) { if (cache[r] == perten_max) calc(r); return cache[r]; } /// modify one value and dirty its cache line - inline void modify(int c, int r, perten value) { matrix[c][r] = value; cache[r] = perten_max; } + inline void modify(int c, int r, perten value) { matrix[r][c] = value; cache[r] = perten_max; } /// modify one condition and dirty relevant cache lines - void toggle(int c, bool v) { if (enabled[c] != v) { enabled[c] = v; for (unsigned r = 0; r < R; r++) if (matrix[c][r] != perten_full) cache[r] = perten_max; } } + void toggle(int c, bool v) { if (enabled[c] != v) { enabled[c] = v; for (unsigned r = 0; r < R; r++) if (matrix[r][c] != perten_full) cache[r] = perten_max; } } inline bool is_enabled(int c) const { return enabled[c]; } private: - void calc(int r) { cache[r] = perten_full; for (unsigned c = 0; c < C; c++) { if (enabled[c]) cache[r] = perten_multiply(cache[r], matrix[c][r]); } } - std::array, C> matrix; + void calc(int r) { cache[r] = perten_full; for (unsigned c = 0; c < C; c++) { if (enabled[c]) cache[r] = perten_multiply(cache[r], matrix[r][c]); } } + std::array, R> matrix; std::array enabled; std::array cache; };