Nihilai Collective Logo

memcpy-decomp

Nihilai Collective

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
template<uint64_t bucket_size, typename load_op_type, uint64_t... indices>
struct memop_runner_impl<bucket_size, load_op_type, std::integer_sequence<uint64_t, indices...>> {
    static constexpr uint64_t chunk_size{ bucket_size < register_width ? bucket_size : register_width };
    using chunk_type = memop_chunk<load_op_type, chunk_size>;

    template<auto... values, typename... arg_types>
    static void impl(std::byte* dst, uint64_t n, arg_types... args) {
        const uint64_t tail_offset = n - bucket_size;
        const mem_chunk<chunk_size> head[]{ chunk_type::load<values...>(indices * chunk_size, args...)... };
        const mem_chunk<chunk_size> tail[]{ chunk_type::load<values...>(tail_offset + indices * chunk_size, args...)... };
        (store_chunk<chunk_size>(dst + indices * chunk_size, head[indices]), ...);
        (store_chunk<chunk_size>(dst + tail_offset + indices * chunk_size, tail[indices]), ...);
    }
};
load ops: where a chunk comes from
struct copy_load {
    template<uint64_t size> static mem_chunk<size> impl(const std::byte* src) {
        mem_chunk<size> chunk;
        pow2_memcpy<size>(&chunk, src);
        return chunk;
    }
};

struct fill_load {
    template<std::byte value, uint64_t size> static mem_chunk<size> impl() {
        mem_chunk<size> chunk;
        pow2_memset::impl<value, size>(&chunk);
        return chunk;
    }
};

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 copies: one masked copy on AVX-512BW
void copy_small(std::byte* dst, const std::byte* src, uint64_t n) {
    const __mmask64 mask = _bzhi_u64(~0ull, n);
    _mm512_mask_storeu_epi8(dst, mask, _mm512_maskz_loadu_epi8(mask, src));
}
small copies: a branch-free quad everywhere else
void copy_small(std::byte* dst, const std::byte* src, uint64_t n) {
    if (n >= 4) {
        const uint64_t inner = static_cast<uint64_t>(n >= 8) << 2;
        const uint64_t outer = n - 4;
        pow2_memcpy<4>(dst, src);
        pow2_memcpy<4>(dst + inner, src + inner);
        pow2_memcpy<4>(dst + outer - inner, src + outer - inner);
        pow2_memcpy<4>(dst + outer, src + outer);
    } else if (n != 0) {
        const uint64_t middle = n >> 1;
        dst[0] = src[0]; dst[middle] = src[middle]; dst[n - 1] = src[n - 1];
    }
}
dispatch: small op, then a fold over pair classes, shared by all three
template<template<uint64_t> typename runner_type, typename small_op_type, typename fallback_op_type, uint64_t... class_indices>
struct fold_dispatcher<runner_type, small_op_type, fallback_op_type, std::integer_sequence<uint64_t, class_indices...>> {
    template<uint64_t pair_size, auto... values, typename... arg_types>
    static bool try_pair(std::byte* dst, uint64_t n, arg_types... args) {
        if (n <= pair_size * 2) {
            runner_type<pair_size>::impl<values...>(dst, n, args...);
            return true;
        }
        return false;
    }

    template<auto... values, typename... arg_types>
    static void impl(std::byte* dst, uint64_t n, arg_types... args) {
        if (n <= small_copy_limit) {
            small_op_type::impl<values...>(dst, n, args...);
        } else if (!(try_pair<(first_pair_size << class_indices), values...>(dst, n, args...) || ...)) {
            fallback_op_type::impl<values...>(dst, n, args...);
        }
    }
};

template<uint64_t max_bytes> using memcpy_dispatcher  = fold_dispatcher<copy_runner, small_memcpy,  memcpy_wrapper,  ...>;
template<uint64_t max_bytes> using memset_dispatcher  = fold_dispatcher<fill_runner, small_memset,  memset_wrapper,  ...>;
template<uint64_t max_bytes> using memmove_dispatcher = fold_dispatcher<copy_runner, small_memmove, memmove_wrapper, ...>;

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):

Lengthsmemcpy_decompstd::memcpySpeedup
1 – 154,9691,0514.73×
1 – 165,9191,0915.42×
1 – 176,3541,1325.62×
1 – 3110,9621,9595.60×
1 – 3211,4871,9975.75×
1 – 3311,8132,0285.83×
1 – 6521,5483,7425.76×

Without AVX-512, on Linux (WSL) with GCC 16 and Clang 24, same workload (MB/s):

LengthsGCC memcpy_decompGCC std::memcpyGCC speedupClang memcpy_decompClang std::memcpyClang speedup
1 – 153,6231,3852.62×3,3781,3722.46×
1 – 164,0011,4652.73×3,7971,4482.62×
1 – 174,1751,5552.69×3,5731,5802.26×
1 – 314,0812,7001.51×4,0652,6791.52×
1 – 324,1122,7751.48×4,2602,7631.54×
1 – 334,2342,8451.49×4,2632,8811.48×
1 – 637,8985,3741.47×8,4775,4681.55×
1 – 647,6665,4511.41×8,5615,5741.54×
1 – 657,8345,5261.42×8,9735,5331.62×
1 – 12715,08611,1991.35×15,80611,2201.41×
1 – 12815,58311,3651.37×16,16811,4151.42×
1 – 12915,35211,6361.32×16,20811,5821.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

Quick Start

Drop in the header
#include "memcpy-decomp.hpp"

int main() {
    char src[64]{}, dst[64]{};
    uint64_t n = 37;
    memcpy_decomp::memcpy_decomp(dst, src, n);
    memcpy_decomp::memcpy_decomp_up_to<64>(dst, src, n);
    memcpy_decomp::memset_decomp<std::byte{ 0x20 }>(dst, n);
    memcpy_decomp::memmove_decomp(dst + 1, dst, n);
}
Build the benchmark suite
git clone https://github.com/nihilai-collective/memcpy-decomp.git
cd memcpy-decomp
cmake -B build -DCMAKE_BUILD_TYPE=Release
cmake --build build --config Release
./build/memcpy-decomp

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.

Platforms: Windows, Linux, macOS · Compilers: MSVC, GCC, Clang · Harness: BenchmarkSuite

View the full benchmark repository →

Results

Platform / Compiler
Loading benchmarks
Contender

Acknowledgments