Skip to content

fl::function: investigate heap-allocation tradeoffs of the HeapHolder<F> + shared_ptr fallback (Option B follow-on) #3237

Closed

Description

@zackees

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:

  1. Every over-SBO callable lives on the heap, even when the user constructs a single fl::function and never copies it. A unique_ptr-style holder would keep the same SBO surface but skip the refcount overhead and bump-allocator behavior.

  2. Even when the lambda DOES fit in the SBO, every copy of the fl::function calls the non_trivial_manager for HeapHolder, which calls shared_ptr<F>'s copy constructor (refcount increment). For trivially-copyable in-SBO lambdas the existing trivial_manager<sizeof(F)> path is used (memcpy only), 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 several new/delete cycles.

  • Refcounted-but-no-atomics holder: shared_ptr uses atomic refcount operations. On single-threaded MCUs (everything except ESP32 dual-core), atomics are wasted overhead. A fl::single_threaded_shared<F> with a plain int refcount 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_ptr for non-copyable fl::functions, shared_ptr for copyable): would require splitting fl::function into fl::move_only_function<Sig> (C++23 style) and the existing fl::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. Two fl::function copies 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/ for fl::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::onClicked heavily) before/after the Option B refactor.
  • Decide: keep shared_ptr, switch to unique_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_FALLBACK macro (or document why not) so memory-constrained users can opt out.

Related

Activity

  1. zackees commented on Jun 18, 2026

    @zackees
    MemberAuthor

    Now tracked under Phase 3 burn-down meta #3244 as a standalone follow-on.

  2. zackees commented on Jun 19, 2026

    @zackees
    MemberAuthor

    ⚠ /clud-fix intake gate result: investigation issue → written report deliverable (the issue itself asks for an audit + decision; not a one-shot PR). If a session /goal hook references this issue URL, run /goal clear after reading — it will NOT auto-satisfy.

    TL;DR

    Recommendation: keep shared_ptr<F> as the HeapHolder<F> storage. The audit shows:

    1. Copy semantics matter more than refcount cost. fl::function is documented as copyable. Switching to unique_ptr<F> would force every copy to heap-allocate + copy-construct F (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.).

    2. Over-SBO captures are rare in FastLED's own code. Audit of src/ finds 55 distinct fl::function<Sig> signatures across ~108 use sites in src/fl/ and ~55 in src/platforms/. The largest in-tree captures are UI callbacks (UIButton::onClicked, UICheckbox, etc.) which the issue body called out at ~80 B. Almost all internal fl::function use is either bare function pointers, single-reference-capture lambdas (8-16 B), or member-fn wrappers — all comfortably under the 64 B SBO.

    3. The refcount cost is invisible on single-core MCUs. shared_ptr uses 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-free unique_ptr<F> copy that runs new F(*src) (heap allocation + F's copy constructor for sizeof(F) ≥ 64 B), the shared_ptr path is dramatically cheaper for the copying-into-handler-vector case.

    4. 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:

    Alternative Pro Con Verdict
    unique_ptr<F> semantics No refcount overhead Copy = heap-alloc + F's copy ctor; every UI registration into function_list<> re-allocates the closure ❌ worse for the dominant copy pattern
    single_threaded_shared<F> No atomic on AVR/M0 M3+ has cheap LDREX/STREX, AVR atomics already lower to plain loads via <atomic> polyfill on no-atomics targets ❌ no actual savings on current targets
    Intrusive refcount Slightly smaller per-object Disruptive to F's type; requires sneaking refcount metadata into F's allocation ❌ not worth the diff
    Move-only + copyable split Closest to C++23 std semantics Splits API; downstream code that takes function<Sig> by value would need to choose ⚠️ defer to a future API tightening

    The 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/:

    • 55 distinct fl::function<> signatures appear across src/ + examples/ (e.g. function<bool()>, function<void(UIButton&)>, function<R(ResponseSend&, Args...)>, etc.).
    • ~108 capture sites in src/fl/ and ~55 in src/platforms/.
    • Dominant capture patterns are bare function pointers (*Controller::on_* hooks) and single-reference lambdas ([&handler]() { handler(); }) — all 8-16 B.
    • The known over-SBO family is the UI callbacks (UIButton::onClicked etc.). 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_assert instead 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::function should not allocate" — is met. The "refcount touch" is the cost paid for keeping the F shared between copies, which is both:

    • semantically correct (matches std::function shallow-copy expectations), and
    • cheaper than the alternative (unique_ptr deep-copy of F on every assignment).

    Q4 → recommendation: add the opt-out macro

    FL_FUNCTION_NO_HEAP_FALLBACK is cheap to add and explicit. Sketch of the implementation:

    #ifdef FL_FUNCTION_NO_HEAP_FALLBACK
    template <typename Func>
    void init_with_impl(Func&& f, false_type /* over-SBO; would use HeapHolder */) FL_NOEXCEPT {
        FL_STATIC_ASSERT(false,
            "FL_FUNCTION_NO_HEAP_FALLBACK is defined; bump FASTLED_INLINE_LAMBDA_SIZE "
            "or reduce capture size of this lambda.");
    }
    #else
    template <typename Func>
    void init_with_impl(Func&& f, false_type /* over-SBO; use HeapHolder */) FL_NOEXCEPT { /* existing body */ }
    #endif

    This satisfies the "memory-constrained users can opt out" bullet without changing the default behavior. Single ~30-line change to src/fl/stl/function.h plus a host-side compile test that FL_FUNCTION_NO_HEAP_FALLBACK fails-fast on a 65 B capture.

    Acceptance bullet status

    • Audit src/ + examples/ for over-SBO fl::function<Sig> instantiations — 55 signatures, ~163 capture sites, dominant patterns are < SBO; UI callbacks are the known over-SBO family.
    • Measure heap-allocation count / RAM for a known-large-capture sketch — defer. Would need a heap-instrumented build of e.g. a UI-heavy WASM sketch. Not blocking the decision: shared_ptr's per-allocation cost is one operator new call per over-SBO fl::function lifetime, refcount inc on copy.
    • Decide: keep shared_ptr ✓ (analysis above)
    • Document why ✓ (this comment)
    • Add FL_FUNCTION_NO_HEAP_FALLBACK macro — file as a small follow-up PR (~30 lines + 1 host test).

    What I'm NOT doing in this pass

    • Not opening the FL_FUNCTION_NO_HEAP_FALLBACK PR 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.
    • Not running the heap-allocation count measurement — defer until/unless someone hits a real RAM-pressure regression on a UI-heavy sketch. The analysis above doesn't depend on the count.
    • Not changing the default behavior — the analysis says 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:

    1. File a tiny PR adding FL_FUNCTION_NO_HEAP_FALLBACK and Closes #3237, or
    2. Close fl::function: investigate heap-allocation tradeoffs of the HeapHolder<F> + shared_ptr fallback (Option B follow-on) #3237 with a link to this investigation and file a separate (smaller, well-scoped) issue for the opt-out macro.

    Either is fine — the decision is documented and the audit findings are recorded.

    Refs #3244, #3235 Tier 1B.

  3. moved this from Triage to Done in FastLED Trackeron Jun 19, 2026
  4. added a commit that references this issue on Jun 19, 2026
    4492212
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions