Skip to content

cf: share the per-rule statistics instead of copying them per lookup - #1583

Closed
rdexel wants to merge 1 commit into
storytold:mainfrom
rdexel:perf/cf-lookup-shared-stats
Closed

rdexel wants to merge 1 commit into
storytold:mainfrom
rdexel:perf/cf-lookup-shared-stats

Conversation

@rdexel

@rdexel rdexel commented Oct 15, 2026

Copy link
Copy Markdown

The problem

CfCache::look is called once per cell while the grid paints. The per-rule statistics — sorted: Vec<f64> of every number in the rule's range, and counts: HashMap<String, usize> of every distinct display value — are computed once and cached correctly, then cloned out of the cache on every lookup:

let st = self.stats.entry(idx).or_insert_with(|| { /* … */ }).clone();

So each lookup costs the size of the rule's range rather than a constant, and the cache is defeated by its own return value.

What it cost

Found while opening a trial-balance workbook: 2 sheets, ~80k cells, 947 rows — three cellIs rules over J11:BD413 (~22.5k cells), plus 19 more rules on the second sheet. Measured with the offscreen snapshot harness on an M5, release build:

load steady-state frame
--sample sales 5.6 ms 0.4 ms
the workbook, before 201 ms ~170 ms
the workbook, after 201 ms ~9.8 ms

~170 ms a frame is about 6 FPS — the grid visibly lagged on any scroll or repaint. sample(1) put 12,441 of 12,528 samples on grid::show → paint_quadrant → grid::look → cf::CfCache::look, dominated by String::clone, hashbrown table construction and memmove/malloc/free. Instrumenting the rule showed the cloned statistics held 18,894 numbers and 8,215 distinct strings, copied per painted cell per rule per frame.

The fix

Hold the statistics behind an Arc so the existing .clone() is a pointer clone. Deref coercion covers every use (st.sorted, st.counts, &st into threshold), so the change is three lines.

No behaviour change: the snapshot render of the workbook is byte-identical before and after (sha256 9f3017833b2510d7a88b3798…).

Tests

  • cf_lookup_does_not_cost_the_size_of_the_rule_range — 500 lookups against a rule over 1k cells vs 20k cells; the cost must not grow with the range. Before the fix: 11.2 ms vs 171.0 ms (15x), fails. After: equal, passes. #[ignore]d with #[allow(clippy::disallowed_methods)], matching recalc_with_range_formulas_scales_linearly.
  • cf_lookup_applies_the_rule_inside_its_range_only — the correctness behind it, run every time.

cargo xtask ci passes: fmt, clippy, test, assets, layers, wasm.

Not addressed here

grid::show constructs CfCache::new() per frame, so the statistics never amortise across frames — numbers_in re-scans the range 3x per frame at ~2.55 ms each, which is ~7.7 ms of the remaining ~9.8 ms. Hoisting the cache into app state needs invalidation on edit, so I left it out of this change. Relatedly, statistics are keyed by rule index while all three rules here share one range and compute identical statistics; keying by range would cut that work 3x→1x. Happy to follow up on either.

🤖 Generated with Claude Code

Painting asks `CfCache::look` for one cell's conditional look at a time, and
the per-rule statistics (the sorted numbers and the duplicate counts) were
cloned out of the cache on every lookup, so each lookup cost the size of the
rule's range rather than a constant. A workbook with three rules over a
22k-cell range spent ~170 ms a frame, about 6 FPS; it now paints in ~9.8 ms.

Holding the statistics behind an `Arc` makes the lookup a pointer clone. No
behaviour change: the offscreen render of the workbook is byte-identical
before and after.

`cf_lookup_does_not_cost_the_size_of_the_rule_range` asserts the cost of 500
lookups does not grow with the rule's range (20x the rows was 15x the time
before the fix, 1x after). It is `#[ignore]`d like the other timing tests;
`cf_lookup_applies_the_rule_inside_its_range_only` checks the values behind
it on every run.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@MichaelMuClaude

Copy link
Copy Markdown

Verified against main (applies clean), including the honest "prove it was slow" step since this is a performance PR:

  • Ran the always-on correctness test (cf_lookup_applies_the_rule_inside_its_range_only) alone against unpatched main: passes, as expected — the clone is wasteful, not wrong.
  • Ran the #[ignore]d timing test alone against unpatched main (--ignored, release build): fails with 1k-cell rule 12.2ms, 20k-cell rule 243.4ms — roughly 20x for 20x the range, consistent with the PR's own measured 15x and well over the 4x tolerance.
  • Applied the full patch: the same timing test passes, and the whole test (500 lookups × 3 reps × 2 range sizes) dropped from 0.84s to 0.07s wall time in this run alone — a visible, independent confirmation of the fix's effect, not just the test's pass/fail.
  • cargo test -p gridcraft-engine --lib → 288 passed, 1 ignored (the timing test, correctly marked), matching expectations.
  • cargo clippy -p gridcraft-engine --lib --tests -- -D warnings and cargo fmt --check -p gridcraft-engine both clean.
  • The fix is exactly as described — Arc<RuleStats> turns the existing .clone() into a pointer clone, deref coercion handles every read site, and no other line changes, which matches "the change is three lines."

Correct, minimal, and well-measured. The honest "not addressed here" section (per-frame cache reconstruction, and the 3x duplicate-stats-per-shared-range opportunity) are real follow-ups but don't block this fix, which stands on its own. Good to merge.

@aiongg

aiongg commented Oct 22, 2026

Copy link
Copy Markdown
Contributor

Superseded by #1136, merged in #2226.

@aiongg aiongg closed this Oct 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants