Power-of-2 memcpy, memset and memmove decomposition · header-only · C++20
What It Is
memcpy-decomp splits a runtime-length memcpy into a few power-of-two copies
whose sizes are known at compile time, so each one lowers to plain register loads and
stores with no library call. It is the technique Jsonifier uses for its small copies, pulled
out so it can be measured on its own.
The same decomposition now covers memset and memmove too. All three run on
one shared engine, the exact code Jsonifier ships, and each is
benchmarked head-to-head against its standard library counterpart.
Why
Take any power of two N and any length n with N ≤ n ≤ 2N. A copy of
N bytes anchored at the front and a copy of N bytes anchored at the back together
cover every byte exactly once or twice and never step outside
[0, n). The overlap is harmless: it rewrites the same bytes with the same values. So a whole
range of lengths shares one pair of fixed-size copies, and the only runtime question is which range
n falls in.
memcpy-decomp makes that question as small as it can. For short lengths it stops asking altogether:
with AVX-512BW, every length from 0 to 64 is one masked load and one masked
store, with the mask built from the length, so a random mix of short lengths has nothing to
mispredict. Bytes outside the mask are never touched, so a read that ends near a page boundary stays
safe. Without AVX-512, lengths 4 to 16 are four overlapping 4-byte copies whose middle pair moves out
by four bytes once n ≥ 8, chosen without a branch, and lengths 1 to 3 are three byte copies
(first, middle, last).
Above that, the ranges are expanded as a || fold over pair classes: class
N takes every length up to 2N. On AVX-512 that is at most two compares for
anything from 65 to 256 bytes, and a compile-time upper bound
(memcpy_decomp_up_to<N>) trims the fold to the classes it can reach.
Earlier versions picked a power-of-two bucket with a switch on
std::bit_width(n), and later with a compile-time binary compare tree. Both still had to
choose between many buckets for short lengths, and with random lengths that choice was the dominant
cost. Removing it for short lengths is where the current version gets its speed.
Short copies need no decision; longer ones need one or two compares.
The Algorithm
pair runner: load every chunk, front and back, then store them all
memop_chunk shifts every pointer in args... by the chunk's offset before
calling the load op, so memcpy and memmove pass their source and
memset passes nothing at all. Because every load lands in a register before the first
store, overlapping buffers are safe, which is what makes the same runner correct for
memmove.
small_copy_limit is 64 with AVX-512BW and 16 without, and the first pair class is the
next power of two above it. pair_class_count<max_bytes> stops the fold at the
largest class a bounded call site can reach, so memcpy_decomp_up_to<15> never
builds a pair class at all. Lengths past 256 bytes fall through to std::memcpy,
std::memset or std::memmove, where the library's bulk paths are the right tool.
memset and memmove
memset takes its fill byte as a template argument
(memset_decomp<std::byte{ 0x20 }>(dst, n)), so every fixed-size store is an
immediate and the fill pattern never touches memory. Every byte gets the same value, so its small
path needs none of memcpy's offset bookkeeping: one store anchored at the front and one at the back
covers any length from 2k to 2k+1, in 8, 4, 2 or 1 byte steps.
memmove reuses memcpy's copy_runner unchanged, since
the runner already loads everything before it stores anything. Only its small path and fallback
differ: small_memmove loads its head and tail before writing either, and anything past
256 bytes goes to std::memmove. On AVX-512BW the masked load completes before the masked
store, so the 0 to 64 byte path is overlap-safe as it stands.
Size Map
0 – 64 bytes · AVX-512BW
One masked load and one masked store. The only compare on
the length is n ≤ 64.
1 – 16 bytes · elsewhere
1 – 3: first, middle and last byte. 4 – 16: four overlapping 4-byte
copies placed without a branch.
17 – 64 bytes · elsewhere
Pair classes 16 and 32: two overlapping copies of the class size,
[0, N) and [n − N, n), split into register-width chunks.
65 – 256 bytes
Pair classes 64 and 128, split into register-width chunks: 2 or 4 copies on AVX-512, 4 or 8
on AVX2, 8 or 16 on SSE/NEON.
257+ bytes
Falls through to std::memcpy. Pruned entirely when the call site's
compile-time bound is 256 or below.
Headline Numbers
Linux · Clang on an AVX-512 runner, 4,096 random-length copies per timed iteration (MB/s):
Lengths
memcpy_decomp
std::memcpy
Speedup
1 – 15
4,969
1,051
4.73×
1 – 16
5,919
1,091
5.42×
1 – 17
6,354
1,132
5.62×
1 – 31
10,962
1,959
5.60×
1 – 32
11,487
1,997
5.75×
1 – 33
11,813
2,028
5.83×
1 – 65
21,548
3,742
5.76×
Without AVX-512, on Linux (WSL) with GCC 16 and Clang 24, same workload (MB/s):
Lengths
GCC memcpy_decomp
GCC std::memcpy
GCC speedup
Clang memcpy_decomp
Clang std::memcpy
Clang speedup
1 – 15
3,623
1,385
2.62×
3,378
1,372
2.46×
1 – 16
4,001
1,465
2.73×
3,797
1,448
2.62×
1 – 17
4,175
1,555
2.69×
3,573
1,580
2.26×
1 – 31
4,081
2,700
1.51×
4,065
2,679
1.52×
1 – 32
4,112
2,775
1.48×
4,260
2,763
1.54×
1 – 33
4,234
2,845
1.49×
4,263
2,881
1.48×
1 – 63
7,898
5,374
1.47×
8,477
5,468
1.55×
1 – 64
7,666
5,451
1.41×
8,561
5,574
1.54×
1 – 65
7,834
5,526
1.42×
8,973
5,533
1.62×
1 – 127
15,086
11,199
1.35×
15,806
11,220
1.41×
1 – 128
15,583
11,365
1.37×
16,168
11,415
1.42×
1 – 129
15,352
11,636
1.32×
16,208
11,582
1.40×
The path is chosen by BenchmarkSuite's CPU detection (BNCH_SWT_HAS_AVX512BW), not by
compiler flags, so any compiler on an AVX-512BW machine takes the masked copy, MSVC included. CPUs
without it, and every macOS ARM runner, take the branch-free quad and pair classes; their numbers are
in the platform tabs below.
Features
Header-only, single C++20 header
Every copy is a compile-time power of two
No length dispatch for 0 to 64 bytes on AVX-512BW: one masked copy
Branch-free 4 to 16 byte copies everywhere else
Register width and AVX-512BW detected per machine (SSE/NEON, AVX2, AVX-512)
Fold-expression dispatch over overlapping pair classes, no jump table
Bounded variant trims the fold at compile time
Falls back to std::memcpy, std::memset and std::memmove for bulk sizes
memset_decomp with a compile-time fill byte
Overlap-safe memmove_decomp on the same engine
Cross-platform CI: MSVC, GCC, Clang on Windows / Linux / macOS
Exhaustive length × alignment sweep with guard bytes on every run
Benchmarked at 4,096 copies per timed iteration
Statistical tie detection via Welch's t-test
MIT licensed
Includes a deliberately pessimized memcpy_decomp_anti_opt for scale
CMake pulls BenchmarkSuite and rt-ut
automatically via FetchContent. Requires C++20. The header itself includes
<benchmarksuite> for its CPU and compiler detection macros, so BenchmarkSuite has
to be on the include path when you drop it into your own project.
Correctness
Every run opens with an exhaustive sweep: every length from 0 to 300,
at every source and destination misalignment from 0 to 31, copied into a buffer surrounded by
guard bytes. Each byte inside the copy is checked against the source, and each byte outside it is
checked to be untouched. The bounded variant is swept the same way at every power-of-two boundary
(0, 1, 2, 3, 4, 7, 8, … 255, 256, 257).
memset_decomp gets the same sweep with a fixed fill byte. memmove_decomp is
swept inside a single buffer, at every source and destination offset from 0 to 63, so source and
destination overlap in both directions, and the whole buffer is compared byte-for-byte against
std::memmove run on a copy.
Before each benchmark, every contender then replays 16 iterations of that test's exact workload into its
own buffer, and the final buffers are compared byte-for-byte against the standard function's. Nothing is
timed until it has been proven correct on the same machine, compiler and input used for the benchmark.
Validation runs across the full
Windows MSVC, Ubuntu GCC, Ubuntu Clang, macOS Clang, and macOS GCC
matrix on every push.
Benchmark Methodology
Throughput is measured in megabytes copied per second (MB/s),
benchmarked against std::memcpy with a runtime length on identical
hardware. Every timed iteration performs 4,096 copies between two
64 KiB buffers. Copy i starts at offset (i × 192) & 0xFF00, plus a small jitter
((i × 5) & 63 on the source, (i × 11 + 3) & 63 on the destination), so
copies land at varied alignments while the address stream stays regular and cache-resident.
Lengths come from a fixed 65,536-entry table generated by a seeded LCG over each test's range. Every
iteration starts 12,347 entries further into the table, so consecutive iterations replay different
length sequences. Every length also passes through a volatile read, so the compiler can
never treat a size as a constant. There are six stages, an
unbounded and a bounded stage for each of memcpy, memset and memmove, each a head-to-head against
std::memcpy, std::memset or std::memmove on the identical
workload, and all run the same twelve ranges: 1–15, 1–16, 1–17, 1–31, 1–32, 1–33, 1–63, 1–64, 1–65,
1–127, 1–128 and 1–129 bytes.
The memset stages fill each destination with a compile-time constant byte. The memmove stages move
within a single buffer, from dst + (n & 15) to dst + 8, so the source
lands before, on or after the destination depending on the length and every move overlaps.
memcpy_decomp
Unbounded variant, carrying every pair class plus the std::memcpy fallback on
every call.
memcpy_decomp_up_to<N>
Bounded variant, with N set to the range's maximum, so only the pair classes that
range can reach are compiled in.
memcpy_decomp_anti_opt · anti_opt_up_to<N>
A deliberately pessimized copy for scale, one per stage: the original power-of-two bucket tree,
with every chunk copy forced out of line and repeated 32 times behind a mutex, a condition
variable, a time-seeded RNG and three heap allocations.
The ranges come in triplets around each power of two from 16 to 128, so each triplet straddles the
edge of a pair class (or of the small-copy limit). For memcpy_decomp a length past the
edge is a rare extra compare; for memcpy_decomp_up_to<N> it can mean one more pair
class compiled in. Each triplet shows what crossing that boundary costs, and the 127–129 triplet
reaches into the 128-byte class.
The harness uses adaptive epoch sampling. The exact iteration
counts, thresholds, and timing bounds for each run are read live from that run's own results CSV,
since they can vary per run. Each epoch runs a fresh batch of iterations, starting at the configured
measured-iteration count and doubling every epoch, and is scored on a trailing window of
k = clamp(iterations / 10, MinK, MaxK) samples. An epoch's score is its
relative standard error plus its
mean shift from the previous epoch.
Sampling continues until the time limit or the total
iteration budget is exhausted, and the lowest-scoring epoch is
kept as the canonical result, whether or not it met the convergence thresholds. That result counts as
converged only if its RSE and mean shift are both at or under their configured thresholds.
Non-converged results are still included in the rankings and in
win/tie/loss tallying, so a result that missed those thresholds should be read with its reduced
statistical confidence in mind.
All results are ranked by throughput. Neighbouring results are checked for a statistical tie
with Welch's t-test on per-iteration timings, using
Bessel-corrected variance and Welch–Satterthwaite degrees of
freedom at roughly 95% confidence. Statistically indistinguishable results are recorded as ties. CPU caches are evicted before each contender's run.
Every range stays at or below 129 bytes: the regime that
small-copy-heavy workloads like serialization actually live in. The CPU, OS, and compiler for each run
are detected at build time and recorded in that platform's result file.