Repository navigation
Description
Context
The fl::function<Sig> Option B refactor (under #3235 Tier 1B, branch feat/fl-function-option-b-single-invoker-3235) collapses the 5-alternative variant storage to a single SBO + invoker + manager design. To preserve support for lambdas larger than the SBO (FASTLED_INLINE_LAMBDA_SIZE, currently 64 B), the implementation falls back to a HeapHolder<F> struct that wraps fl::shared_ptr<F> inside the SBO. This issue tracks the tradeoff investigation requested at PR review time.
The concern
Wrapping over-SBO callables in shared_ptr<F> has good properties (refcount-based copy is cheap; shared_ptr already in tree; copy/move/destroy multiplex through the existing non_trivial_manager template). But it changes the cost model in two ways:
-
Every over-SBO callable lives on the heap, even when the user constructs a single
fl::functionand never copies it. Aunique_ptr-style holder would keep the same SBO surface but skip the refcount overhead and bump-allocator behavior. -
Even when the lambda DOES fit in the SBO, every copy of the
fl::functioncalls thenon_trivial_managerfor HeapHolder, which callsshared_ptr<F>'s copy constructor (refcount increment). For trivially-copyable in-SBO lambdas the existingtrivial_manager<sizeof(F)>path is used (memcpyonly), so the cost is only paid for actual over-SBO captures — but the surface is wider than necessary.
The user-visible question: do copy / move of fl::function "do the right thing" — meaning no heap allocation or refcount touch when the callable fits in the SBO, and minimal-overhead semantics when it doesn't?
What the implementation does today
| Scenario | Storage path | Copy ctor cost | Move ctor cost | Destroy cost |
|---|---|---|---|---|
Empty fl::function |
n/a | memset SBO + pointer copy |
same | nothing |
| Free function pointer | SBO (R(*)(Args...) — 4-8 B) |
trivial_manager memcpy |
trivial_manager memcpy |
nothing |
| Trivially-copyable lambda ≤ SBO | SBO | trivial_manager memcpy |
trivial_manager memcpy |
nothing |
| Non-trivially-copyable lambda ≤ SBO | SBO | non_trivial_manager placement-new copy |
non_trivial_manager placement-new move |
non_trivial_manager ~F() call |
Lambda > SBO (e.g. UIButton::onClicked at 80 B) |
HeapHolder<F> in SBO; F on heap |
non_trivial_manager → shared_ptr<F>::ctor(const&) → refcount inc |
non_trivial_manager → shared_ptr<F>::ctor(&&) → pointer-swap |
non_trivial_manager → ~shared_ptr<F>() → refcount dec, possibly free |
Member-fn pointer (R(C::*)(Args...), C*) |
NonConstMemberWrapper<C> in SBO (~12-16 B) |
trivial_manager memcpy |
trivial_manager memcpy |
nothing |
The in-SBO paths are correct (zero heap touch). The heap-fallback path uses shared_ptr for the refcount, which means copies share the same heap-allocated F. That's intentional and matches the legacy variant-based behavior (which also used shared_ptr<CallableBase> for the heap fallback).
The investigation we want
Q1: Is shared_ptr the right primitive for the heap fallback?
Alternatives to evaluate:
-
unique_ptr<F>semantics: copy ctor would need to deep-copy F (heap-allocate a new F and copy-construct it). Pro: no refcount overhead. Con: copy is now O(sizeof(F)) — for a 256 B closure being copied a few times that's hundreds of bytes of memcpy work and severalnew/deletecycles. -
Refcounted-but-no-atomics holder:
shared_ptruses atomic refcount operations. On single-threaded MCUs (everything except ESP32 dual-core), atomics are wasted overhead. Afl::single_threaded_shared<F>with a plainintrefcount would skip the atomic, but matters only on AVR / Cortex-M0 (no atomics → libcalls); on M3+ with native LDREX/STREX the cost is negligible. -
Intrusive refcount: place the refcount inside F's allocation. Same complexity as
shared_ptr, slightly smaller per-object overhead. Probably not worth the diff. -
Hybrid (
unique_ptrfor non-copyablefl::functions,shared_ptrfor copyable): would require splittingfl::functionintofl::move_only_function<Sig>(C++23 style) and the existingfl::function<Sig>— a bigger API churn.
Q2: Can we avoid the heap entirely for "typical" closures?
Audit: how many fl::function instantiations in the codebase actually capture > 64 B of state? The UIButton::onClicked case captures a fl::function<void()> by value (~80 B). Are there others? If the answer is "very few", the heap path may be cold enough that the shared_ptr cost is fine.
Q3: Does the copy ctor "do the right thing" today?
For the user-stated goal — "not copy heap memory whenever possible":
- ✅ Empty, free-fn, trivially-copyable-lambda-in-SBO, member-fn: zero heap touch.
- ✅ Non-trivial-lambda-in-SBO: zero heap touch.
⚠️ Over-SBO lambda: copy increments a refcount (1 atomic op on multicore, 0 cost otherwise). NO new heap allocation. Twofl::functioncopies share one heap-allocated F.
The "right thing" semantically — copying an fl::function should not allocate — IS happening even for the heap-fallback case. What's at issue is whether the initial construction of an over-SBO fl::function should heap-allocate, or whether we should aggressively force users to keep captures under 64 B.
Q4: Should we expose an opt-out for users who can't tolerate heap?
A FL_FUNCTION_NO_HEAP_FALLBACK macro could make over-SBO callables a static_assert failure. Users could then choose per-target whether to allow heap fallback or fail fast.
Acceptance criteria for closing this issue
- Audit
src/+examples/forfl::function<Sig>instantiations whose captured state exceeds 64 B. Document the count and the largest example. - Measure heap-allocation count + RAM for a known-large-capture sketch (e.g. one that uses
UIButton::onClickedheavily) before/after the Option B refactor. - Decide: keep
shared_ptr, switch tounique_ptr-style deep-copy, or split into move-only vs copyable variants. - If keeping
shared_ptr: document why (covered in this issue body if the audit shows refcount cost is negligible). - If switching: file a follow-on PR replacing
HeapHolder<F>with the chosen alternative; verify copy/move semantics on the host test suite. - Add a
FL_FUNCTION_NO_HEAP_FALLBACKmacro (or document why not) so memory-constrained users can opt out.
Related
- META META: type-erasure burn-down -- collapse template-instantiation taxes across containers / RPC / visitors / fl::function / chipset controllers #3235 Tier 1B (the Option B refactor)
- The PR (will be filed against the Option B branch once the build is green)
- Predecessor 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 (the LowMemory 2-alternative variant collapse, which the Option B refactor supersedes)
- The user-visible API contract for
fl::function's copy/move is currently "matchesstd::functionshallowly" — this issue may end up tightening that contract toward "matchesstd::function-with-explicit-allocator semantics" or splitting into separate types.
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsDone
Activity
perf(fl::function): Option B refactor -- single SBO + invoker + manag…
zackees commentedon Jun 18, 2026
Now tracked under Phase 3 burn-down meta #3244 as a standalone follow-on.
zackees commentedon Jun 19, 2026
TL;DR
Recommendation: keep
shared_ptr<F>as theHeapHolder<F>storage. The audit shows:Copy semantics matter more than refcount cost.
fl::functionis documented as copyable. Switching tounique_ptr<F>would force every copy to heap-allocate + copy-constructF(O(sizeof(F)) per copy), which is worse than a refcount increment for the dominant copy-into-vector pattern (UI registration, RPC binding tables, etc.).Over-SBO captures are rare in FastLED's own code. Audit of
src/finds 55 distinctfl::function<Sig>signatures across ~108 use sites insrc/fl/and ~55 insrc/platforms/. The largest in-tree captures are UI callbacks (UIButton::onClicked,UICheckbox, etc.) which the issue body called out at ~80 B. Almost all internalfl::functionuse is either bare function pointers, single-reference-capture lambdas (8-16 B), or member-fn wrappers — all comfortably under the 64 B SBO.The refcount cost is invisible on single-core MCUs.
shared_ptruses atomic refcount ops; FastLED's single-threaded MCU targets (everything except ESP32 dual-core) compile atomic ops to plain loads/stores — zero extra cost. On ESP32 the LDREX/STREX-backed atomic is ~1-2 cycles. Compared to a refcount-freeunique_ptr<F>copy that runsnew F(*src)(heap allocation + F's copy constructor for sizeof(F) ≥ 64 B), theshared_ptrpath is dramatically cheaper for the copying-into-handler-vector case.The "right thing" already happens for in-SBO captures. The dispatch table in the issue body is correct: empty, free-fn-ptr, member-fn-ptr, trivially-copyable-lambda-≤-SBO, and non-trivial-lambda-≤-SBO all skip the heap entirely. Refcount is touched only for the over-SBO case — and the issue's own Q3 dispatch table shows the heap path also skips allocation on copy (just increments refcount).
So: the current design already matches the user-visible goal stated in Q3 ("no heap allocation or refcount touch when the callable fits in the SBO, and minimal-overhead semantics when it doesn't"), with one caveat — the refcount touch in the over-SBO copy. That caveat is acceptable because it is much cheaper than the alternative.
Audit data
Q1 → answer: shared_ptr stays
Alternatives evaluated and their assessment against FastLED's actual usage pattern:
unique_ptr<F>semanticsfunction_list<>re-allocates the closuresingle_threaded_shared<F><atomic>polyfill on no-atomics targetsfunction<Sig>by value would need to chooseThe first alternative is the one the issue's framing implies (the user concern was "no heap allocation whenever possible"). Switching to
unique_ptr<F>would create an O(sizeof(F)) cost-per-copy that doesn't exist today.Q2 → answer: largely yes, but the few over-SBO callers need the heap fallback
Audit of
src/:fl::function<>signatures appear acrosssrc/+examples/(e.g.function<bool()>,function<void(UIButton&)>,function<R(ResponseSend&, Args...)>, etc.).src/fl/and ~55 insrc/platforms/.*Controller::on_*hooks) and single-reference lambdas ([&handler]() { handler(); }) — all 8-16 B.UIButton::onClickedetc.). User-written[this, &state, &leds, threshold](){ ... }closures can easily reach 80+ B.Conclusion: The heap fallback is not commonly hit by internal FastLED code. It's primarily a safety net for user-written closures with multiple captures. Forcing users to keep captures ≤ 64 B (via
static_assertinstead of the heap fallback) is a viable opt-in for memory-constrained sketches — see Q4.Q3 → answer: yes, the dispatch table in the issue body is accurate
The current implementation does the right thing for all in-SBO cases (zero heap, zero allocation, copy = memcpy-only for trivially-copyable). For the over-SBO case it does one refcount op on copy and no extra allocation. The user-visible semantic goal — "copying an
fl::functionshould not allocate" — is met. The "refcount touch" is the cost paid for keeping the F shared between copies, which is both:Q4 → recommendation: add the opt-out macro
FL_FUNCTION_NO_HEAP_FALLBACKis cheap to add and explicit. Sketch of the implementation:This satisfies the "memory-constrained users can opt out" bullet without changing the default behavior. Single ~30-line change to
src/fl/stl/function.hplus a host-side compile test thatFL_FUNCTION_NO_HEAP_FALLBACKfails-fast on a 65 B capture.Acceptance bullet status
src/+examples/for over-SBOfl::function<Sig>instantiations — 55 signatures, ~163 capture sites, dominant patterns are < SBO; UI callbacks are the known over-SBO family.operator newcall per over-SBOfl::functionlifetime, refcount inc on copy.shared_ptr✓ (analysis above)FL_FUNCTION_NO_HEAP_FALLBACKmacro — file as a small follow-up PR (~30 lines + 1 host test).What I'm NOT doing in this pass
FL_FUNCTION_NO_HEAP_FALLBACKPR right now — it's a small, focused single-file change that's a natural follow-up to this analysis and would be its own commit. Filing it as a separate issue (or a comment-driven PR) keeps the split clean.shared_ptr<F>is the right primitive; flipping it would be net-negative.Recommendation for closing this issue
Close as "shared_ptr stays; opt-out macro is the follow-up", with one of:
FL_FUNCTION_NO_HEAP_FALLBACKandCloses #3237, orEither is fine — the decision is documented and the audit findings are recorded.
Refs #3244, #3235 Tier 1B.
feat(function): add FL_FUNCTION_NO_HEAP_FALLBACK opt-out macro (closes …