Repository navigation
Description
Goal
FastLED's core value prop is "smallest possible footprint for LED control on embedded MCUs." Meta #3224 (closed) demonstrated that surgical #if FL_PLATFORM_HAS_LARGE_MEMORY gating can recover 22% of flash on a 64 KB part. This meta tracks the next architectural axis: replacing per-template-instantiation codegen taxes with shared runtime-typed thunk layers (the type erasure pattern that fl::vector_basic already pioneered under fl::vector<T>).
This is a burn-down meta: file sub-issues against it, link PRs, retire items as they land. Each sub-issue carries its own concrete byte target on a defined target sketch + board. Close this meta when ≥75% of the catalog has landed or been formally deferred with rationale.
Why type erasure now
The Tier 3H finding from #3224 — TypedRpcBinding<Sig>::invokeWithReturn consuming ~2.1 KB per registered method — is the entry point. But it's the symptom of a broader pattern. After dispatching five parallel sub-agent audits across the codebase, the same shape appears in at least six independent subsystems:
| Subsystem | Per-instantiation tax (estimate) | Pattern |
|---|---|---|
fl::unordered_map<K, V> |
~2.6 KB / instance | Hot methods (rehash_internal, find_slot, operator[]) are pure pointer/bitset arithmetic that doesn't depend on K,V |
fl::flat_map<K, V, Less> |
~300 B / instance × ~30 call sites | lower_bound, upper_bound, operator[] are pure binary search over byte storage |
fl::variant<...>::visit_fn<T, V> thunk table |
~50-164 B × (alternatives × visitors) | json_value has 10 alts × ~9 visitors = ~330 thunks (~6.7 KB on LPC845) |
fl::function<Sig> 5-alternative variant |
~2 KB / signature × ~25-30 signatures | 5 alternatives × 4 ops × N sigs; MemberCallable variants are dead code in production |
| JSON visitors (per (visitor, T) pair) | ~700 B per visitor | Quadratic codegen tax over (10 alternatives × 9 visitors) |
RPC dispatch templates (TypedRpcBinding, JsonArgConverter, TypeToJson) |
~2.1 KB per signature | The Tier 3H item; entirely re-implementable as RuntimeRpcBinding + ~150 B trampoline |
ClocklessController<TIMING, PIN, ORDER> (32 chipset families) |
~0.8-2 KB per (chipset × pin × order) | Already nearly type-erased on RMT5; runtime variant viable on ESP32/Teensy/RP2040/WASM |
Estimated total flash recovery across the catalog: 25-50 KB on a kitchen-sink sketch (e.g. AutoResearch on ESP32-S3 with the full RPC + JSON surface and 4-6 LED controllers). LPC8xx / AVR builds were already squeezed in #3079 and #3224 so the headroom for those is smaller — but the same patches help every embedded target.
Measurement methodology
Use bash bloat <board> --example <sketch> (works as of #3225 across ESP32 + arm-none-eabi via fbuild symbols delegation). Compare top-N symbols before and after each PR. Acceptance threshold per sub-issue: ≥80% of the predicted savings on the primary target sketch.
Baseline (today, master + #3232):
Board: lpc845brk
Example: AutoResearch (LowMemory mode)
Total flash: 51,538 B RAM: 9,959 B Headroom: ~14 KB
Top contributors (per arm-none-eabi-nm --print-size):
1 2,270 B autoResearchLowMemorySetup
2 2,142 B fl::TypedRpcBinding<string(int×4)>::invokeWithReturn ← Sub-issue A target
3 1,982 B fl::JsonBuilder::on_token
4 1,576 B fl::Rpc::handle
5 1,024 B autoResearchLowMemorySetup lambda#2
6 792 B fl::function<string(int×4)>::InlinedLambda::invoke_lambda
7 762 B fl::basic_string::write(char const*, unsigned int)
8 660 B __clzdi2 (libgcc)
9 650 B fl::JsonTokenizer::parse
10 628 B fl::unordered_map<string, RpcEntry>::rehash_inline_no_resize ← Sub-issue C target
Sub-issues to file
Tier 1 — highest leverage, well-scoped
| # | Title | Target tax | Predicted saving | Difficulty | Notes |
|---|---|---|---|---|---|
| A | RuntimeRpcBinding: replace TypedRpcBinding<Sig> with a non-template binding + per-Sig trampoline |
~2.1 KB / Sig | ~1.5-1.8 KB / Sig (one-time +1 KB amortized) | medium-hard | Tier 3H from #3224. Per-Sig template tax → per-Sig trampoline (50-150 B). Phase via FL_PLATFORM_HAS_LARGE_MEMORY opt-in; ESP32/Teensy hot path can keep templates. Detailed design + risk in sub-issue. |
| B | fl::function<Sig> Option B: single SBO + invoker/manager fn ptrs |
~2 KB / Sig | ~1.5 KB / Sig on Large-memory; ~25-35 KB cumulative | medium | Replaces the 5-alternative variant with one struct holding (invoker, manager, char[SBO]). Member-fn support survives as a thin wrapper. Audit confirmed zero production uses of &Class::method outside one test file. Side-effect: fixes a latent UB in memcpy-based InlinedLambda copy. |
| C | unordered_map_basic: pointer/bitset arithmetic into a non-template base |
~2.6 KB / instance | ~3 KB on LPC845, ~6-9 KB on full builds | medium | Mirror fl::vector_basic pattern. rehash_internal, rehash_inline_no_resize, find_slot, find_index are all signature-agnostic. unordered_set gets the win for free as a wrapper. |
Tier 2 — high leverage, more invasive
| # | Title | Target tax | Predicted saving | Difficulty | Notes |
|---|---|---|---|---|---|
| D | flat_map_basic: shared binary-search core |
~300 B / instance × ~30 instances | ~6-9 KB on full builds | easy | lower_bound, upper_bound, operator[] are pure pointer arithmetic + less_fn(const void*, const void*). Easiest container win after unordered_map_basic. |
| E | json_visit_dispatch: non-template dispatch core for visitors |
~700 B per visitor × ~9 visitors | ~2.5-3.5 KB on LPC845, ~5+ KB on Large-memory | medium | Replaces per-(visitor × T) operator() overloads with json_convert_to_<int/bool/float/string>_core(tag, storage, out). Templated wrapper handles final type narrowing only. SizeVisitor / IsArrayVisitor reduce to tag-table lookups in Phase 1 (free ~250 B trial). |
| F | ClocklessControllerRuntime: runtime-timing variant for ESP32/Teensy/RP2040/WASM |
~0.8-2 KB per chipset specialization | ~8-25 KB on Blink-like sketches with many chipsets | medium-hard | Preserves FastLED.addLeds<CHIPSET, PIN, ORDER>(...) API surface. AVR / LPC8xx / ESP8266 keep template path (cycle-tight bit-banging needs compile-time constants). Gated via FL_USE_RUNTIME_CLOCKLESS. |
Tier 3 — modest wins, defer until Tier 1/2 measured
| # | Title | Target tax | Predicted saving | Difficulty | Notes |
|---|---|---|---|---|---|
| G | Variant trivial-destructor / trivial-copy collapse | ~50-164 B × N (T, V) pairs | ~2-3 KB on variant-heavy targets (json_value) | hard | Share destroy_fn across is_trivially_destructible Ts (collapse to noop_destroy). Share copy_fn/move_fn across trivially-copyable Ts (collapse to memcpy(storage, other, size) thunks parameterized at runtime by sizeof(T)). Doesn't touch visit semantics. |
| H | deque_basic shadow class |
~250 B / instance | ~150 B per future instantiation | easy | Mirror vector_basic. Only 1-2 deque instantiations today (deque<char> for json, deque<u8> for parlio). Limited ROI but cheap to land alongside Tier 2D. |
| I | Visitor warning-string outlining (formatter-only) | ~150-250 B / visitor × ~9 visitors | ~1-2 KB | easy | Today each visitor inlines a fl::to_string(value, 6) warning formatter that anchors basic_string machinery. Outline to a single format_warning_value(tag, storage) helper that only links if any visitor actually emits a warning at runtime. |
Tooling dependency
- fbuild#594 —
bash bloatBOARD_CHIP_MAP arm support landed in feat(bloat): delegate nm + ELF path resolution to fbuild symbols (arm support) #3225. ELF-on-overflow flag (--allow-overflow) also landed. - fbuild#627 — daemon-crash-under-multi-worktree filed during the META: LPC845 flash-budget Phase 2 — grow headroom from 1.4 KB to ~6-10 KB for feature capacity #3224 arc; still affects iteration but doesn't block.
Both of these are documented in agents/docs/binary-size-analysis.md so any future agent picking up sub-issues has the right measurement workflow.
Predecessors
- Meta META: LPC845 64 KB flash bloat hunt -- clear 11 KB overage to unblock FASTLED_LPC_RX_SCT_WS2812=1 #3079 (closed 2026-06-15) — LPC845 64 KB flash bloat hunt; first surgical-gating arc
- Meta META: LPC845 flash-budget Phase 2 — grow headroom from 1.4 KB to ~6-10 KB for feature capacity #3224 (closed 2026-06-18) — LPC845 flash-budget Phase 2; sub-issues A/B/D/E/G shipped via PRs perf(lpc): close meta #3224 -- Tier 1A/1B/2D/2E/3G (-14.6 KB flash, -1.3 KB RAM, 10× headroom) #3226 + perf(lpc): close meta #3224 -- Tier 1B/2D/2E/3G + RAM gate (-10.3 KB flash, -1.3 KB RAM, on top of #3226) #3232
- LPC845 bloat: fl::function variant emits 6.3 KB of copy/move/destroy clones across RPC dispatch signatures #3077 / perf(fl::function): collapse variant to {free_fn, inlined_lambda} on Low-memory (closes #3077, -3.9 KB on LPC845) #3084 — already-shipped fl::function variant collapse on Low-memory (precursor to Tier 1 item B above)
- PR feat(bloat): delegate nm + ELF path resolution to fbuild symbols (arm support) #3225 —
bash bloatarm support (unblocks measurement on this meta)
Acceptance for closing this meta
- At least 4 of {A, B, C, D, E} closed via merged PRs
- Tier 1 items A and B both addressed (the two biggest leverage items)
- Each sub-issue's predicted byte saving is verified within 25% accuracy on its target sketch
-
bash bloat <board>workflow documented inagents/docs/binary-size-analysis.md(already mostly there post-feat(bloat): delegate nm + ELF path resolution to fbuild symbols (arm support) #3225) - Tier 3 items either filed as separate trackers or explicitly deferred with rationale
How to claim a sub-issue
- File the sub-issue against this meta with the title pattern
[Type-Erasure] <subsystem>: <approach>and a concrete byte target on a named sketch+board. - Run
bash bloat <board> --example <sketch>before starting work to capture the baseline. - Implement with whatever pattern fits (
*_basicshadow class, runtime dispatch core, trampoline approach, etc.). - Run
bash bloat <board> --example <sketch>after and post the delta in the PR. - Reference this meta in the PR body via
Closes #<sub-issue>so it tracks against the burn-down.
Out of scope
- ESP32 RMT5 driver internals (already nearly fully type-erased post-feat(channels): compile-time Bus binding via templated ChannelConfig (eliminates Channel API binary bloat) #2428).
- AVR bit-bang drivers (compile-time-constant timing is a hard requirement for cycle-tight asm).
fl::shared_ptr/fl::optional/fl::tuple(container audit found these already optimal; the savings would be < 100 B each).- Application-level / sketch-side bloat (covered by the user's own sketch refactoring; the meta is focused on framework-level reusable wins).
Sub-agent audit reports
The five parallel audits that informed this meta are summarized in the table above. Full reports (one per subsystem) available on request; each covers current cost, proposed design, savings estimate, risk assessment, and migration plan. They follow the same shape and arrived at consistent conclusions, lending confidence to the catalog numbers.
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsDone
Activity
zackees commentedon Jun 18, 2026
Large-memory baseline added: Teensy 4 / AutoResearch
What this confirms
fl::Channel::showPixelsat 5,608 B for a single chipset specialization — exactly the Tier 2F (ClocklessControllerRuntime) leverage point. A sketch with 4 chipset variants (e.g. Blink with WS2812 + APA102 + SK9822 + WS2811) would pay 4× this tax (~22 KB) where the runtime variant collapses to one ~6 KB body.AutoResearchRemoteControl::registerFunctionspartitioned at 4,700 + 4,506 = 9.2 KB across two LTO chunks — this is the per-methodrpc.bind()registration code. With ~10 methods registered, Tier 1A (RuntimeRpcBinding) would drop this to ~2-3 KB total. Net win on Teensy 4: ~6-7 KB just from the registration path.fl::Rpc::handleat 2,536 B (down from META: LPC845 64 KB flash bloat hunt -- clear 11 KB overage to unblock FASTLED_LPC_RX_SCT_WS2812=1 #3079 / META: LPC845 flash-budget Phase 2 — grow headroom from 1.4 KB to ~6-10 KB for feature capacity #3224 work) — the dispatch core is now well-trimmed, but per-SigTypedRpcBinding<>::invokeWithReturninstantiations (each ~2 KB) live separately and aren't in the top 12 list because each is amortized across LTO partitions. They exist in the binary —nm --print-size | grep TypedRpcBinding | awkwould show the aggregate.On the LPC845 baseline (also in the meta body)
Same patterns, different magnitudes. The Tier 1 items (A, B, C) hit both targets equally.
ESP32-S3 sketch measurements
5 sketches (AutoResearch, Animartrix, Chromancer, Json, FxNoiseRing) were queued for ESP32-S3 bloat analysis. The build hit FastLED/fbuild#627 (zccache daemon wedge under concurrent worktree use) on AutoResearch — typical of the current daemon flakiness. Per-sub-issue PRs will rebuild + measure on their target sketch + board fresh; the cross-sketch ranking from LPC845 + Teensy 4 establishes the priority order, and individual sub-issues will validate against whichever sketch best exercises their target subsystem.
zackees commentedon Jun 18, 2026
Reopening: PR #3238 closed Tier 1B item B (
fl::functionOption B, -9.2 KB on Teensy 4) but the meta also tracks Tier 1A (RuntimeRpcBinding), Tier 1C (unordered_map_basic), Tier 2D (flat_map_basic), Tier 2E (json_visit_dispatch), Tier 2F (ClocklessControllerRuntime), and Tier 3 G/H/I. Per the meta's own acceptance criteria, ≥4 of {A, B, C, D, E} must close via merged PRs; one down, three to go.zackees commentedon Jun 18, 2026
Implementation findings after Tier 1B (PR #3238 merged)
While working through this meta I prototyped Tier 2D (
flat_map_basic) and started on Tier 1C (unordered_map_basic). Honest finding: the per-instantiation savings predicted by the original audit don't materialize on the AutoResearch sketch because that build only has 2 distinct instantiations each offlat_map<>andunordered_map<>. The audit's "~6-9 KB on kitchen-sink builds" prediction assumed ~30 distinct map types; AutoResearch is nowhere near that.Concrete measurements
Tier 2D prototype outcome
I built the type-erased binary-search helpers (
flat_map_lower_bound_idx/upper_bound_idx) withFL_NO_INLINEto defeat LTO inlining. On AutoResearch:The implementation is correct. The leverage just isn't there on a 2-instance build. The
vector_basicprecedent works becausefl::vector<T>is instantiated for many T's across the codebase. Forflat_mapandunordered_mapon focused sketches like AutoResearch, the per-instance savings (~80-150 B from sharing inner loops) are smaller than the per-call thunk overhead (~30-50 B × N call sites).What this means for the meta
The "≥4 of {A, B, C, D, E} closed" acceptance criterion was based on the assumption that each Tier item would be a positive-value ship. That assumption holds for Tier 1B (fl::function Option B, shipped via #3238, −9.2 KB Teensy 4) because every embedded build instantiates ~25-30 distinct
fl::function<Sig>signatures. It does not hold for Tier 1C/2D on small / focused sketches because the per-call thunk overhead can dominate.Revised acceptance proposal
The original framing was right that this meta is a burn-down, not a single-PR effort. But I'd revise the success criterion to be more measurement-driven:
Under that framing:
rpc.bind()calls will demonstrate it).__attribute__((flatten))at call sites, or hand-rolled assembly thunks that fit in a few bytes).ClocklessControllerRuntime): still high-leverage — the audit specifically estimated 8-25 KB on Blink-like sketches with multiple chipsets. That's a different dimension of leverage (per-chipset, not per-container) and should still pay off.I'm leaving the meta open. The realistic short-term win-list is:
RuntimeRpcBinding) — biggest remaining single-PR leverage. Has the cleanest design (per-Sig template → per-Sig trampoline). I'll tackle this as a follow-up.ClocklessControllerRuntime) — different leverage axis; sketches with multiple chipsets will demonstrate.Tier 1C/2D should be revisited once the codebase has more container instantiations OR a CI target sketch is specifically chosen to exercise them.
What I'd recommend the next agent picking this up do
switchon a small argument-type table, not a function-pointer-thunk-per-comparison. The leverage scales with method count, not instance count.Reopening + commenting on the meta rather than silently letting it expire because the "≥4 of 5" math doesn't add up on a sketch-by-sketch basis.
perf(flat_map): type-erase lower_bound / upper_bound binary search (#…
perf(unordered_map): type-erase probing-sequence helper (#3235 Tier 1…
perf(json): replace SizeVisitor + IsArrayVisitor with direct tag chec…
fix(unity-build): re-sort fl/stl/_build.cpp.hpp includes alphabetical…
zackees commentedon Jun 18, 2026
Forward link: remaining Tier 1A / 2E Phase 2 / 2F / 3 G/H/I items rolled into Phase 3 burn-down at #3244.
perf(fl::function): Option B refactor -- single SBO + invoker + manag…
perf(deque): deque_basic ring-buffer + grow-policy helpers (#3250 / #…
feat(function): add FL_FUNCTION_NO_HEAP_FALLBACK opt-out macro (closes …