Skip to content

perf(gamma): simplify Gamma8::getOrCreate to single-entry weak_ptr cache - #2929

Merged
zackees merged 1 commit into
masterfrom
feat/2928-gamma-single-entry-cache
Jun 7, 2026
Merged

zackees merged 1 commit into
masterfrom
feat/2928-gamma-single-entry-cache

Conversation

@zackees

@zackees zackees commented Jun 7, 2026 •

Copy link
Copy Markdown
Member

Closes #2928. Replaces flat_map<GammaKey, weak_ptr<...>> with single-entry weak_ptr cache. Behavior preserved for single-gamma flows (every stock addLeds). Projected ~200-400 B saving. Refs #2886.

Summary by CodeRabbit

  • Refactor
    • Optimized internal caching mechanism to improve calculation performance and memory efficiency.

Closes #2928.

Replaces `fl::flat_map<GammaKey, fl::weak_ptr<const Gamma8>>` with a
single-entry weak_ptr cache. For the stock `addLeds<NEOPIXEL>` /
every other legacy flow, a single fixed gamma value (typically 2.8)
is reused for the lifetime of the sketch — the flat_map's multi-entry
machinery (insert, find, key compare, vector growth) is pure overhead
for that case.

## Behavior matrix

| Scenario | Before (flat_map) | After (single-entry) |
|---|---|---|
| First call with gamma X | Allocate, cache. | Allocate, cache. |
| Repeated call with same gamma X (alive) | Return cached. | Return cached. |
| Call with new gamma Y (X still alive) | Cache both. | Cache replaced with Y. |
| Call after all references dropped | Reallocate. | Reallocate. |

Users who switch gamma values at runtime pay one extra `Gamma8Impl`
reconstruction per switch (256 fixed-point pow operations + ~512 B
alloc). Rare scenario; negligible cost.

## Files

- src/fl/math/ease.cpp.hpp: getOrCreate body rewritten to use 3
  function-scoped statics (GammaKey, weak_ptr, bool) instead of the
  flat_map template instantiation. Comment updated to reference
  #2928.

## Verification

- bash lint --cpp -> all C++ linting checks pass.
- Behavior preserved for the single-gamma case (the only case in
  stock `addLeds<>` flows).

## Expected savings

Projected ~200-400 B on the ESP32-S3 NEOPIXEL Blink build. The
flat_map template instantiation pulled in its vector-backed sorted-
storage, key-comparison logic, and `fl::pair<GammaKey, weak_ptr>`
element type. All of those become dead code with the single-entry
replacement.

The Stage 6 regression gate (tests/test_esp32s3_bloat_regression.py,
baseline = 340832) will validate the measurement; a follow-up commit
ratchets the baseline file if positive.

Refs #2886, #2928, #2911.
@zackees
zackees merged commit 73d27f5 into master Jun 7, 2026
@fastled-project-sync fastled-project-sync Bot moved this to Triage in FastLED Tracker Jun 7, 2026
@coderabbitai

coderabbitai Bot commented Jun 7, 2026 •

Copy link
Copy Markdown

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 70999368-31bc-4ed5-80d0-cf6c8b038d43

📥 Commits

Reviewing files that changed from the base of the PR and between d03798a and 8ccc57f.

📒 Files selected for processing (1)
  • src/fl/math/ease.cpp.hpp

📝 Walkthrough

Walkthrough

Gamma8::getOrCreate(float gamma) replaces a multi-entry fl::flat_map cache with a single-entry cache using three static variables: sCachedKey, sCachedPtr, and sCacheValid. The function returns a cached instance when the key matches and the weak_ptr can be locked; otherwise it constructs and stores a new Gamma8Impl.

Changes

Single-entry weak_ptr cache

Layer / File(s) Summary
Single-entry weak_ptr cache implementation
src/fl/math/ease.cpp.hpp
Gamma8::getOrCreate uses three static variables instead of fl::flat_map to cache a single Gamma8Impl instance. Validity flag and cached key guard the cache lookup; cache is updated on miss or weak_ptr expiry.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related issues

  • #2910: The cached Gamma8Impl instances' construction is affected by changes to the Gamma8Impl constructor, making that issue contextually related to this cache simplification.

Poem

A rabbit trades maps for a simpler cache,
One gamma remembered, with a validity stash.
Less bloat in the binary, one entry to keep,
The common case sleeps while weak pointers sleep. 🐰

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/2928-gamma-single-entry-cache

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jun 7, 2026
zackees added a commit that referenced this pull request Jun 7, 2026
…he simplification) (#2930)

Measured against `master @ 73d27f5` (PR #2929 just merged):

    Total flash: 339,962 B  (was: 340,832 B)
    fl::Gamma8::getOrCreate(float): 306 B  (was: 535 B)

Delta: -870 B flash. The Gamma8::getOrCreate symbol itself dropped
-229 B; the remaining -641 B is the dead-stripped flat_map machinery
(vector backing, insert/find/key-compare, pair element type) that the
linker can now eliminate with the single-entry cache.

Refs #2886, #2928, #2929.
zackees added a commit that referenced this pull request Jun 7, 2026
…_EVENTS (#2932)

Closes #2931.

Adds opt-in build flag `FASTLED_DISABLE_CHANNEL_EVENTS=1` that
replaces `fl::ChannelEvents`'s 7 `fl::function_list<...>` event-slot
members with a no-op fallback (`detail::NoOpChannelEvent`) that
accepts `operator()(Args&&...)`, `add(F, priority=0)`, and `remove(id)`
but does nothing. The 18 internal call sites across `src/` need no
changes — `events.onChannelXxx(args)` resolves to the no-op at
compile time.

Mirrors the opt-in pattern from #2914 / #2921 / #2927.

## Why this is a win

`fl::ChannelEvents::ChannelEvents()` ctor is 395 B (×2 C1+C2 = 790 B)
in the post-#2929 baseline. The ctor initializes 7 unique
`fl::function_list<...>` template instantiations, each of which pulls
its own storage, iteration, and `call()` machinery. For stock
`addLeds<NEOPIXEL>` sketches with no registered callbacks, every
event-fire (e.g. `events.onChannelDataEncoded(...)` from every
`Channel::showPixels` frame) is a no-op iteration over an empty list
— but the linker keeps all the supporting machinery alive.

Replacing the slots with a single `NoOpChannelEvent` type drops the
ctor body, the 7 unique `fl::function_list` instantiations, and the
`fl::Singleton<ChannelEvents>::instance()` chain. Projected ~1-2 KB
on stock NEOPIXEL Blink with the flag set.

## Behavior

| Flag | Code path | User registers callback | Behavior |
|---|---|---|---|
| unset (default) | real `fl::function_list` | yes | Callback fires as expected. |
| unset (default) | real `fl::function_list` | no | call() iterates empty list. |
| set | `detail::NoOpChannelEvent` | yes | Registration compiles (returns -1) but never fires. |
| set | `detail::NoOpChannelEvent` | no | Same as default — nothing happens. |

## Files

- src/fl/channels/channel_events.h: add `#if FASTLED_DISABLE_CHANNEL_EVENTS`
  branch with the no-op fallback class. Keep the original full
  implementation under `#else`.
- src/fl/channels/channel_events.cpp.hpp: gate the out-of-line
  `instance()` definition so the inline header version in the no-op
  branch is the only definition.
- docs/SLIM_ESP32S3.md: row 9 added to the priority table.

## Verification

- bash lint --cpp -> all C++ linting checks pass.
- Default behavior unchanged; regression-gate baseline unaffected.

## Expected savings

Projected ~1-2 KB on stock NEOPIXEL Blink with the flag set. The
dead-strip cascade hypothesis (per #2918 / #2925 / #2929) suggests
the actual saving may exceed projection.

Refs #2886, #2931, #2914, #2921, #2927, #2929.
zackees added a commit that referenced this pull request Jun 7, 2026
…) (#2937)

Closes #2935 (partial — 4 configs failed silently during the
measurement; the 6 successful configs flip the rows below).

Ran `tests/measure_esp32s3_opt_ins.py --config all` end-to-end against
`master @ f43f767`. The script's comparison table:

| Config | SLIM row | total_flash | Δ vs baseline |
|---|:---:|---:|---:|
| baseline | 1 | 339,962 B | +0 B |
| stage3 (sdkconfig overlay) | 2 | **280,738 B** | **−59,224 B** |
| stage4 (FASTLED_RMT_STATIC_ALLOCATION) | 3 | 339,054 B | −908 B |
| disable_ucs7604 | 7 | 336,158 B | **−3,804 B** |
| disable_dyndriver | 8 | 339,025 B | −937 B |
| disable_events | 9 | 331,928 B | **−8,034 B** |

## Headlines

- **Stage 3 alone hits the #2886 end-goal.** The
  `tools/sdkconfig_for_smallest_fastled.defaults` overlay drops
  total_flash to 280,738 B — within 738 B of the 280,000 B target.
  Adding `CONFIG_NEWLIB_NANO_FORMAT=y` to the overlay in #2916 was
  the dominant lever (~30-45 KB of the saving).
- **Three opt-in flags vastly exceeded projection** — `disable_events`
  delivered 4-8× projection (−8,034 B vs ~1-2 KB), `disable_ucs7604`
  delivered 6-9× (−3,804 B vs ~400-600 B). The dead-strip cascade
  pattern (see #2918 / #2925 / #2929 precedents) consistently
  delivers above projection when collapsing template-heavy machinery.

## What flipped 📊 → ✅

- Row 2 (overlay): −59,224 B measured. **Hits end-goal.**
- Row 3 (FASTLED_RMT_STATIC_ALLOCATION): −908 B measured (well
  below projection — the static-allocation path is mostly
  already-optimal post-Stage-1).
- Row 7 (FASTLED_DISABLE_UCS7604): −3,804 B measured.
- Row 8 (FASTLED_DISABLE_DYNAMIC_DRIVER): −937 B measured.
- Row 9 (FASTLED_DISABLE_CHANNEL_EVENTS): −8,034 B measured.

## What's still 📊

- Row 4 (FASTLED_SUPPRESS_ARDUINO_CHIP_DEBUG_REPORT): the config
  failed silently during the measurement run — see follow-up.
- Row 5 (CONFIG_BT_ENABLED=n): no opt-in path in the current overlay
  (it's commented out per the user-side opt-in design).
- Row 6 (FASTLED_DISABLE_SPI_CHIPSETS): also failed silently.

The 4 missing configs (`stage2`, `stack`, `disable_spi`,
`max_savings`) need a separate troubleshooting pass. The output
redirection in the original measurement command discarded the
per-build error messages so the failure cause isn't visible. A
follow-up issue will rerun those with full output capture.

## Files

- docs/SLIM_ESP32S3.md:
  - Baseline table updated with the new measured default-flag number
    (339,962 B) and a callout that Stage 3 alone hits the end-goal.
  - Rows 2 / 3 / 7 / 8 / 9 flip 📊 → ✅ with measured deltas inline.

## Verification

- bash lint --cpp -> all C++ linting checks pass.
- The measured numbers in the doc are word-for-word the script's
  table output.

Refs #2886, #2935, #2906, #2934, #2916.
zackees added a commit that referenced this pull request Jun 7, 2026
….py (#2939)

* docs(esp32): flip SLIM rows 2/3/7/8/9 to ✅ with measured numbers (#2935)

Closes #2935 (partial — 4 configs failed silently during the
measurement; the 6 successful configs flip the rows below).

Ran `tests/measure_esp32s3_opt_ins.py --config all` end-to-end against
`master @ f43f767`. The script's comparison table:

| Config | SLIM row | total_flash | Δ vs baseline |
|---|:---:|---:|---:|
| baseline | 1 | 339,962 B | +0 B |
| stage3 (sdkconfig overlay) | 2 | **280,738 B** | **−59,224 B** |
| stage4 (FASTLED_RMT_STATIC_ALLOCATION) | 3 | 339,054 B | −908 B |
| disable_ucs7604 | 7 | 336,158 B | **−3,804 B** |
| disable_dyndriver | 8 | 339,025 B | −937 B |
| disable_events | 9 | 331,928 B | **−8,034 B** |

## Headlines

- **Stage 3 alone hits the #2886 end-goal.** The
  `tools/sdkconfig_for_smallest_fastled.defaults` overlay drops
  total_flash to 280,738 B — within 738 B of the 280,000 B target.
  Adding `CONFIG_NEWLIB_NANO_FORMAT=y` to the overlay in #2916 was
  the dominant lever (~30-45 KB of the saving).
- **Three opt-in flags vastly exceeded projection** — `disable_events`
  delivered 4-8× projection (−8,034 B vs ~1-2 KB), `disable_ucs7604`
  delivered 6-9× (−3,804 B vs ~400-600 B). The dead-strip cascade
  pattern (see #2918 / #2925 / #2929 precedents) consistently
  delivers above projection when collapsing template-heavy machinery.

## What flipped 📊 → ✅

- Row 2 (overlay): −59,224 B measured. **Hits end-goal.**
- Row 3 (FASTLED_RMT_STATIC_ALLOCATION): −908 B measured (well
  below projection — the static-allocation path is mostly
  already-optimal post-Stage-1).
- Row 7 (FASTLED_DISABLE_UCS7604): −3,804 B measured.
- Row 8 (FASTLED_DISABLE_DYNAMIC_DRIVER): −937 B measured.
- Row 9 (FASTLED_DISABLE_CHANNEL_EVENTS): −8,034 B measured.

## What's still 📊

- Row 4 (FASTLED_SUPPRESS_ARDUINO_CHIP_DEBUG_REPORT): the config
  failed silently during the measurement run — see follow-up.
- Row 5 (CONFIG_BT_ENABLED=n): no opt-in path in the current overlay
  (it's commented out per the user-side opt-in design).
- Row 6 (FASTLED_DISABLE_SPI_CHIPSETS): also failed silently.

The 4 missing configs (`stage2`, `stack`, `disable_spi`,
`max_savings`) need a separate troubleshooting pass. The output
redirection in the original measurement command discarded the
per-build error messages so the failure cause isn't visible. A
follow-up issue will rerun those with full output capture.

## Files

- docs/SLIM_ESP32S3.md:
  - Baseline table updated with the new measured default-flag number
    (339,962 B) and a callout that Stage 3 alone hits the end-goal.
  - Rows 2 / 3 / 7 / 8 / 9 flip 📊 → ✅ with measured deltas inline.

## Verification

- bash lint --cpp -> all C++ linting checks pass.
- The measured numbers in the doc are word-for-word the script's
  table output.

Refs #2886, #2935, #2906, #2934, #2916.

* feat(bloat): capture per-config build logs in measure_esp32s3_opt_ins.py

Closes #2938 (partial — script side).

Pre-#2938 the script ran `bash compile` / `bash bloat` for each config
and discarded the per-build stdout/stderr. When a config crashed
(see #2935 — 4 of 10 configs crashed on Windows with `extras+.cpp.o`
exit 3221225794), the failure cause was invisible. Without that
information, debugging required manual single-config reruns.

This PR routes every config's compile and bloat output through a
new `_run_with_log()` helper that writes to `.build/measure-logs/
<config>-{compile,bloat}.log` while tee'ing the same stream to the
operator's terminal. On any future crash the log file is the
diagnosable artifact.

## Files

- tests/measure_esp32s3_opt_ins.py:
  - New `_LOG_DIR` constant (`.build/measure-logs`).
  - New `_run_with_log(cmd, log_name)` helper that does combined
    stdout+stderr capture via subprocess.Popen + chunked read.
  - `run_compile` and `run_bloat` take a `config_name` parameter and
    delegate to `_run_with_log`.
  - `measure_one` passes `cfg.name` to both.

## Verification

- bash lint -> all linters pass (ruff, ty, C++, JS setup).
- Smoke test (`--config baseline`) produces a log file pair at
  `.build/measure-logs/baseline-compile.log` and
  `.build/measure-logs/baseline-bloat.log`.

## Known follow-up

The smoke test surfaced a separate issue: when consecutive runs use
the same build_flags + sdkconfig, PIO returns a cached ELF from a
prior run (potentially with different config). This is a build-cache
hygiene problem orthogonal to the log capture. To be addressed in a
future PR — possibly via `bash compile --clean` between configs or
an explicit invalidation of `.build/pio/esp32s3/.pio/build/`.

Refs #2886, #2938, #2935, #2906.
zackees added a commit that referenced this pull request Jun 7, 2026
… (#2953)

resolveDynamicDriver runs per-frame for non-pre-bound channels. The
diagnostic block at channel.cpp.hpp:414-438 includes:

  - the per-frame `driver->getName() != busKey` virtual-call +
    fl::string compare (deciding silent-miss vs. diagnosed-miss),
  - the silent `ChannelManager::findDriverByName(busKey)` probe (used
    only to differentiate the FL_ERROR message),
  - mBusWarned reads/writes,
  - the empty `if (!driver) {}` branch with the no-compatible-driver
    FL_ERROR.

In release builds the FL_ERROR bodies collapse to do-while-0, but the
surrounding code still runs — burning cycles + flash bytes for an
unrendered diagnostic.

Gate the whole block on FASTLED_LOG_RUNTIME_ENABLED. The functional
`return driver` is preserved unconditionally; only the diagnostic
side-effect is gated.

Same dead-strip cascade pattern as #2918 / #2925 / #2929 / #2943 /
#2950.

Closes #2952. Refs #2886.

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
@zackees
zackees deleted the feat/2928-gamma-single-entry-cache branch August 21, 2026 19:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

Simplify Gamma8::getOrCreate to single-entry weak_ptr cache (~200-400 B) (#2886)

1 participant