Skip to content

perf: take std::function, a re-tested word skip and two mask rounds off the hot paths - #112

Merged
Andste82 merged 1 commit into
mainfrom
perf/hot-path-dispatch-and-varint
Aug 9, 2026
Merged

Andste82 merged 1 commit into
mainfrom
perf/hot-path-dispatch-and-varint

Conversation

@Andste82

@Andste82 Andste82 commented Aug 9, 2026

Copy link
Copy Markdown
Member

One consolidated optimization-and-cleanup pass on the maxspeed profile. Every
change in it has a number; two that measured neutral were tried and dropped
rather than committed.

Measurements

Instructions/op under Callgrind — bash bench/run_callgrind.sh, the deterministic,
machine-independent figure this repo's head-to-head table is built on. Same host,
same -O3 build, before = main @ fe0df0a.

Workload before after delta
encode: u64 array (1000) 38 046 35 046 −7.9 %
encode: typical message 266 224 −15.8 %
decode: u64 array (1000) 44 839 43 830 −2.2 %
decode: typical message 1 329 1 199 −9.8 %
Raw before / after tables
before                                          after
Workload                    instr/op     bytes  Workload                    instr/op     bytes
--------                    --------     -----  --------                    --------     -----
encode: u64 array (1000)       38046      9491  encode: u64 array (1000)       35046      9491
encode: typical message          266        37  encode: typical message          224        37
decode: u64 array (1000)       44839      9491  decode: u64 array (1000)       43830      9491
decode: typical message         1329        37  decode: typical message         1199        37

bench (MB/s) and perf (cycles/op) both still run and move the same way, but
this host's wall-clock spread on the array rows is ±10 % run to run, so they are
not the evidence — the Ir table is.

What moved, and why

Each item was found by callgrind_annotate on the workload it shows up in, and
re-measured on its own.

1. std::function in the nested-dispatch path (−81 Ir on decode: typical,
together with the parser fold below).
dispatchLevel took its per-field
callback as const std::function&, so every read() of a sub-message
constructed one, invoked through its _M_invoker after an emptiness test, and
destroyed it through its manager pointer. The std_function.h lines were ~13 %
of the workload's profile. It is now a template on the callable; the two call
sites pass a stateless no-op (skipPayload) and a two-pointer lambda (read),
so the instantiation count is bounded and the body inlines into both.

2. utf8Valid re-tested its word-skip condition per character (−42 Ir on
encode: typical, ~−60 on decode: typical).
The loop asked "are eight bytes
left?" once per byte, so a short ASCII payload paid four branches per character:
validating "sofab" cost ~62 instructions, a quarter of the whole
encode: typical message. The word skip and the byte scan now each run to
completion before the other is considered.

3. spread7's last two rounds are an add (−3 000 Ir on encode: u64 array,
exactly 3 instructions per element).
Once the 7-bit groups are laid out, each
round's two halves partition the live bits — w == (w & keep) + (w & move)
exactly — so (w & keep) | ((w & move) << k) is w + (2^k − 1) * (w & move).
That drops one mask and one OR per round. The first round cannot use it (it
would need w pre-masked to 56 bits in a register of its own, which costs back
more than it saves). Verified equivalent over 20 M random values plus every
single-bit and every low-mask input before it went in, and pinned in-tree by the
existing varintWidthSweep().

4. getVarintWindowed's single-byte peel (−1 000 Ir on decode: u64 array).
It read p[0] separately, then loaded the eight-byte word it needs anyway. The
test now comes off that word. Also (b9 & 0x7f) > 1 || (b9 & 0x80) folds to
b9 > 1 — the legal tenth bytes are 0x00 and 0x01 and nothing else, so it is
the same predicate in one compare.

5. Float scalar/array byte loops. The four or eight wire bytes were built
with a shift loop GCC did not fold into a store. New detail::storeLittleBits /
loadLittleBits memcpy on little-endian and keep the byte-at-a-time form for
big-endian hosts only.

Tried, measured neutral, not included

  • Rewriting the varint length as msb * 9 + 73 to fold the +1 into the
    constant: identical instruction count (GCC already emits bsr; xor $0x3f and a
    lea either way).
  • error_ | limitExceeded_ instead of || in the top-level loop: 1 198 → 1 198.

I did not touch topCallback_. Replacing it with a function-pointer sink saves
~60 Ir on decode: typical, but it makes IStreamInline — the documented
callback surface — one indirect hop worse, and the only way to keep the bench
honest about that is to pay the same hop in the bench adapter. Trading one public
path's cost for another's is not a win.

Cleanup in the same PR

  • The field-header parser existed twice — once in parseTopLevel, once
    copied into dispatchLevel — and the copies had already drifted: the nested
    one shipped without §6.2's ARRAY_MAX ceiling on a fixlen array's count word
    until fix(decode): a schema bound outranks the reassembly cap (#86) #103 put it back. They are now one parser: parseFieldTag (the header
    word and ID_MAX) plus parseFieldMeta (§4.6's fixlen word, §4.7/§4.8's count
    and element word, ARRAY_MAX), composed by parseFieldHeader for the top
    level, which owns the one rule that is the top level's own — a dangling
    SequenceEnd is INVALID there and the close inside a sequence. 70 lines
    deleted
    , with the check order in both loops byte-for-byte what it was.
  • headerParsersEnforceCeilings() can now state the invariant at full
    strength
    : it asserts there is exactly one site that decodes a field header,
    instead of checking that each of however many sites happens to carry the
    ceilings. A second copy is a regression whether or not it is complete on the
    day it appears.
  • A doc block describing a function that no longer exists, deleted; the wire()
    documentation moved back onto wire() (it had come to sit on consumed()).

Why behaviour is unchanged

The two rewrites that could plausibly change behaviour are pinned by differential
tests against independent references, not by inspection:

  • utf8ValidatorSweep() (new) compares utf8_valid against a direct
    transcription of Unicode Table 3-7, sharing no code, table or loop shape
    with it, over ~45 000 cases: every one of the 256 byte values and 26 crafted
    multi-byte sequences (valid edge, overlong, surrogate, out-of-range, truncated,
    bad-continuation) placed at every offset 0..17 inside an ASCII run with 0..17
    trailing bytes — so every atom in turn crosses, starts on and ends on an
    eight-byte boundary, and every truncation distance is covered. Plus ASCII runs
    of every length 0..64. It passes unmodified against the pre-change header,
    which is the point: it asserts the behaviour, not the rewrite.
  • varintWidthSweep() (already in tree) pins spread7/gather7
    byte-exactly against a reference varint encoder over every width, both
    boundaries of every width and a pseudo-random spread, in the windowed and the
    byte-at-a-time paths.

Verified locally:

  • ctest green in Debug and Release, under GCC 15 and Clang.
  • The whole test_roundtrip suite and the shared-vector suite green under
    ASan + UBSan (-fno-sanitize-recover=all) — relevant because
    getVarintWindowed now takes its eight-byte load before the single-byte
    branch; its callers all guarantee the documented VARINT_MAX_BYTES window.
  • 81/81 shared vectors plus 11/11 invalid_utf8 vectors, byte-exact.
  • The non-strict build (SOFAB_STRICT_UTF8=0) still compiles clean, and
    utf8_valid still evaluates in a constant expression (static_assert),
    including a surrogate reject at a 16-byte offset.

The big-endian legs of storeLittleBits / loadLittleBits are the byte loops
they replaced, unchanged; no ppc64 cross toolchain is available here, so CI's
QEMU leg is what confirms them.

README

The Instruction counts (Callgrind) table's last column is updated to the new
figures. The two C columns are the earlier joint run's — only this library's code
moved, and I cannot re-run corelib-c-cpp's script — so the prose now says
exactly that instead of continuing to claim all four were measured together.

…ff the hot paths

Five measured changes on the maxspeed profile, plus the cleanup they made
possible. Every figure is instructions/op under Callgrind (bench/run_callgrind.sh),
which is what this repo measures with because it is deterministic and
machine-independent.

  Workload                    before     after     delta
  encode: u64 array (1000)    38 046    35 046    -7.9 %
  encode: typical message        266       224   -15.8 %
  decode: u64 array (1000)    44 839    43 830    -2.2 %
  decode: typical message      1 329     1 199    -9.8 %

1. dispatchLevel took its per-field callback as `const std::function&`, so every
   `read()` of a sub-message built one, invoked through it twice and destroyed it
   through its manager pointer; the std::function machinery was ~13 % of the
   `decode: typical message` profile. It is now a template on the callable. The
   two call sites pass a stateless no-op and a two-pointer lambda.

2. utf8Valid re-tested its eight-byte ASCII-skip condition once per character, so
   a short ASCII payload paid four branches a byte -- validating the five-byte
   string of the shared `typical message` workload cost ~62 instructions. The
   word skip and the byte scan now each run to completion before the other is
   considered.

3. spread7's last two rounds are spelled as an add. Once the 7-bit groups are
   laid out, each round's two halves partition the live bits, so
   `(w & keep) | ((w & move) << k)` is exactly `w + (2^k - 1) * (w & move)` --
   one mask and one OR less per round, three x86 instructions off every varint
   the encoder writes.

4. getVarintWindowed took its single-byte fast path off a separate byte load of
   p[0] before loading the eight-byte word it needs anyway; the test now comes
   off that word. The tenth-byte overflow test `(b & 0x7f) > 1 || (b & 0x80)`
   folds to `b > 1`, which is the same predicate.

5. The float scalar/array paths built their four or eight wire bytes with a shift
   loop that GCC did not fold into a store. New detail::storeLittleBits /
   loadLittleBits keep the byte-at-a-time form for big-endian hosts only.

Cleanup in the same pass:

- The field-header parser existed twice, at the top level and inside a sequence,
  and the copies had already drifted once: the nested one shipped without the
  §6.2 ARRAY_MAX ceiling on a fixlen array's count word until #103. They are now
  one parser (parseFieldTag + parseFieldMeta, composed by parseFieldHeader for
  the top level, which owns the dangling-SequenceEnd rule). 70 lines gone.
- headerParsersEnforceCeilings() can now assert the invariant at full strength --
  exactly one site decodes a field header -- instead of checking that each of
  however many sites happens to carry the ceilings.
- Dropped a doc block for a function that no longer exists, and moved the wire()
  documentation back onto wire() (it sat on consumed()).

Behaviour is unchanged, and the two rewrites that could plausibly change it are
pinned by differential tests against independent references:

- utf8ValidatorSweep() (new) compares utf8_valid against a direct transcription
  of Unicode Table 3-7 over ~45 000 cases: every byte value and every interesting
  multi-byte sequence at every offset 0..17 inside an ASCII run, so each atom in
  turn crosses, starts on and ends on an eight-byte boundary. It passes
  unmodified against the pre-change header.
- varintWidthSweep() already pins spread7/gather7 byte-exactly against a
  reference varint over every width, both boundaries of every width and a
  pseudo-random spread, windowed and byte-at-a-time.

Full suite green in Debug and Release under GCC 15 and Clang, under
ASan+UBSan, and against all 81 shared vectors plus the 11 invalid_utf8 ones.
@Andste82
Andste82 merged commit e185494 into main Aug 9, 2026
9 checks passed
@Andste82
Andste82 deleted the perf/hot-path-dispatch-and-varint branch August 9, 2026 10:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant