Skip to content

bloat: inline-storage fast path in fl::basic_string::write (skip variant dispatch for the common case) #2976

Closed as not planned

Description

@zackees

@
Tracked in #2974.

Why this symbol matters

fl::basic_string::write(const char*, fl::size) is 1,268 B on ESP32-S3 — rank #7 in the FastLED bloat report and the only symbol in the 1-4 KB band that is NOT dominated by the logging subsystem. Every other 1-4 KB heavy hitter goes away (or shrinks) when FASTLED_LOG_VERBOSITY=0; this one stays put because it is the runtime storage-mode switcher for every fl::string.

The constraint for #2974 is that logging stays enabled, so going after this symbol is one of the few levers we have that does not touch the log path. It is also a force-multiplier: fl::sstream::operator<< overloads route through basic_string::write, so every formatted log line, every assertion message builder, and every fl::to_string(...) pays this dispatch cost.

Current dispatch cost (verified)

src/fl/stl/basic_string.cpp.hpp lines 225-304:

fl::size basic_string::write(const char* str, fl::size n) {
    fl::size newLen = mLength + n;

    if (isNonOwning()) {                              // tag check #1+#2 (ConstLiteral || ConstView)
        // ... promote view -> inline or heap ...
    }
    if (hasHeapData() && heapData().get().use_count() <= 1) {  // tag check #3 + atomic load
        // ... in-place heap append, maybe grow() ...
    } else if (hasHeapData()) {                       // tag check #4
        // ... copy-on-write to a fresh holder ...
    }
    if (newLen + 1 <= mInlineCapacity) {              // finally — the inline fast case
        fl::memcpy(inlineBufferPtr() + mLength, str, n);
        mLength = newLen;
        inlineBufferPtr()[mLength] = 0;
        return mLength;
    }
    // inline -> heap promotion ...
}

So for the common case (fl::string in inline mode, write fits in the 64-byte buffer) we currently execute:

The variant tag itself lives next to the discriminator (_tag == Empty means inline mode — see src/fl/stl/variant.h line 113 and basic_string.h line 502: bool isInline() const { return mStorage.empty(); }). It is a cheap byte load + compare, but we are doing it four times in a row plus carrying full branch-target sequences for paths the inline-mode caller will never take.

Proposed fast path

Add a single early-exit gate before any of the variant logic:

fl::size basic_string::write(const char* str, fl::size n) {
    fl::size newLen = mLength + n;

    // Fast path: inline-mode string with room to spare.
    // mInlineOffset == 0 means "no inline buffer attached" (e.g. constructed
    // from a span or moved-from); mStorage.empty() means we are currently
    // in inline mode (no heap, no literal, no view). Both must hold.
    if (mInlineOffset != 0 && mStorage.empty() && newLen + 1 <= mInlineCapacity) {
        char* buf = inlineBufferPtr();
        fl::memcpy(buf + mLength, str, n);
        buf[mLength + n] = 0;
        mLength = newLen;
        return mLength;
    }

    // ... existing slow path (variant dispatch, COW, heap promote) ...
}

Key properties:

  • Single combined branch (empty() is _tag == Empty, the cheapest tag check possible).
  • One inlineBufferPtr() call held in a local instead of two recomputations of this + mInlineOffset.
  • Returns before touching hasHeapData(), isNonOwning(), or any of their tag compares.
  • No semantic change — every condition the fast path requires is already a precondition of the existing inline branch at line 285.

Estimated savings

  • Direct: ~200-400 B on the basic_string::write(const char*, fl::size) symbol itself, because the compiler can lift the inline-mode store into a tiny prelude and tail-call / cold-call the variant logic.
  • Indirect: faster path for every fl::sstream::operator<< overload (these all funnel through write), which amplifies through FL_WARN, FL_INFO, FL_DBG, fl::to_string, fl::ostringstream, and assertion-message construction. Even with logging enabled, fewer instructions per log line.
  • Bonus: the cold path stays the same size — we are not duplicating code, just hoisting a guard.

Notes for reviewer

  • Trade-off: a few bytes of fast-path prelude vs the four tag compares + branch targets it skips. Net should be negative (smaller). Worth confirming with bash bloat esp32s3 before/after.
  • This pairs naturally with any future work to mark the slow path FL_COLD / __attribute__((cold)) so the compiler favors the inline case in straight-line layout.
  • basic_string::append and the write(char) / write(u8) single-byte paths funnel into this same function (write(&c, 1) at line 218), so the fast path benefits them transitively.
    @

Activity

  1. zackees commented on Jul 29, 2026

    @zackees
    MemberAuthor

    I implemented the proposed fast path exactly as specified and measured it on ESP32-S3 Blink. It is a regression, not a saving — so I'm not opening a PR.

    Measurement

    Same worktree, same toolchain, only basic_string.cpp.hpp toggled between builds. Reproduced twice with byte-identical results:

    write(char const*, unsigned int) total flash
    baseline (origin/master) 1,151 B 393,983 B
    with proposed fast path 1,191 B 394,027 B
    delta +40 B +44 B

    Why the estimate didn't hold

    The issue predicted ~200–400 B "because the compiler can lift the inline-mode store into a tiny prelude and tail-call / cold-call the variant logic." At -Os the compiler is already laying the function out that way — the four tag comparisons are cheap byte loads it has folded into the existing control flow.

    Adding an explicit early-exit doesn't remove that work; it duplicates the inline store. The fast path emits its own memcpy + NUL-terminate + length store, and the original inline branch at the bottom still has to exist for the paths that fall through (non-owning promoted to inline, heap COW that lands inline). So the function gets one extra copy of the store sequence and one extra branch, and grows.

    Also worth noting: the issue's stated baseline of 1,268 B is stale. The symbol is 1,151 B on current master, so ~117 B has already come off it through other work since filing.

    What I verified beyond size

    The change itself is behaviorally sound — 357/357 host tests pass, and string_memory_bugs, string_append_concat and string_comprehensive are clean under ASAN/UBSAN. The problem is purely that it costs bytes instead of saving them.

    The runtime argument (fewer tag checks per write, amplified across every sstream::operator<<) is untested and I'd expect it to be in the noise — these are byte loads against an already-hot cache line, next to a memcpy.

    Recommendation

    Closing as not-planned: the specific approach in this issue makes the symbol bigger. The parent goal in #2974 stands, but write would need a different lever — the duplicated-store problem means any "hoist a guard" variant likely has the same shape. Something that removes a path (e.g. splitting the non-owning promotion out into a cold [[gnu::noinline]] helper so the hot function keeps only the inline + heap-append cases) seems more promising than adding one.

    Happy to reopen if you want the runtime side measured, or a different variant tried.

  2. moved this from Triage to Done in FastLED Trackeron Jul 29, 2026
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