CAFS, minus the counting

If an array of ten million integers holds only a thousand distinct values, you don’t need to sort it. You count it. A new paper sorts such arrays 2–3× faster than pdqsort, and it compares itself only against sorts that don’t count. So I gave it something that counts.

Context

CAFS (“Cache-Aware Frequency Sort”, v2 posted 19 October, code) targets integer columns where the number of distinct values K is far smaller than the length N: status codes, country ids, enum columns. These get sorted constantly in analytics engines. A comparison sort pays O(N log N) whatever K is. A radix sort pays one pass per key byte.

CAFS is a hash-count sort. It walks the array once, counts every distinct value in a hash table, sorts the K (value, count) pairs, and writes each value back count times. Around that core, the paper adds:

The paper reports 1.7–3.1× over pdqsort and 1.2–2.3× over Google’s vqsort when K ≪ N. The benchmark covered 592,770 measurement rows on a Core i5-12400F with uint64 keys, against five general-purpose sorts.

The question

None of those five baselines count. The paper’s future-work section promises a std::unordered_map hash-count baseline and says informal runs show CAFS winning “by orders of magnitude”. v2 doesn’t include it.

So counting was never measured on its own. Three things I wanted to know:

  1. How close does an ordinary hash-map count get to CAFS?
  2. What does the AVX2 bucket add? That is an ablation: same algorithm, different table.
  3. What happens on skewed data? The paper’s grid is uniform only, and its conclusion lists skewed inputs as an open question.

Setup

The counting contenders share one emit step:

template <class Pairs>
static void emit(Vec& v, Pairs& kv) {          // kv: (value, count)
    std::sort(kv.begin(), kv.end());
    auto out = v.begin();
    for (auto& [k, c] : kv) out = std::fill_n(out, c, k);
}

static void count_ankerl(Vec& v) {
    ankerl::unordered_dense::map<Key, u64> m;  // a popular open-source hash map
    for (Key x : v) ++m[x];
    auto kv = std::move(m).extract();
    emit(v, kv);
}

CAFS does the same thing, except it radix-sorts the pairs once there are 256 or more of them. At large K that favors CAFS.

The contenders:

The inputs:

Every output is checked: the first repetition of each cell against std::sort, later ones for sortedness, and every ablation run against std::sort. The machine is a 4-vCPU KVM guest on a 2.1 GHz Xeon with AVX-512, 2 MiB of L2 per core and a 260 MiB shared L3. I used g++ 13.3 with -O3 -march=x86-64-v3. Each benchmark ran pinned to one core, 5 repetitions per cell, and I report medians. I couldn’t pin the CPU frequency, and the same cell can move 20–30% between separate runs. Treat gaps under about 1.2× as ties. All numbers below are at N = 10M unless noted.

Results

Uniform keys.

keys, distribution, K pdqsort hash-map count CAFS, bucket swapped for hash map CAFS
uint64, uniform, 8 4.75 3.72 2.74 2.64
uint64, uniform, 1,000 12.6 4.24 4.91 4.67
uint64, uniform, 16,384 16.9 5.74 6.05 5.60
int32, uniform, 16,384 21.8 4.41 4.94 3.86
uint64, Zipf, 65,536 15.7 7.35 8.40 14.0
uint64, Zipf, 262,144 18.2 11.9 13.2 23.8
int32, Zipf, 262,144 17.5 11.1 10.4 20.7

ns per element, N = 10M. The last three columns come from one ablation run, so they compare directly. pdqsort comes from the main grid. Its int32 K = 16,384 cell is bimodal (two of five reps at ~15 ns), which is also the spike in the int32 panel above.

CAFS time ÷ hash-map-count time, median of 5. Below 1× means CAFS is faster. Hover for values.

What the two charts and the ablation say:

The paper’s “orders of magnitude” claim is about std::unordered_map, and it didn’t hold here either. Across all 176 grid cells (including a fourth input, keys 0..K−1, where nothing in this post changes), CAFS ran between 0.8× (a loss) and 8.4× the speed of a std::unordered_map count, with a median of 2.7×. The largest ratios come from two places: K = 1M on 1M elements, where CAFS has fallen back to pdqsort, and K ≤ 8, where it skips the table.

Why Zipf breaks it

I re-ran CAFS’s own estimator and sizing code on the inputs, then replayed its bucket loop to count spills (diag.cpp):

N = 10M, Zipf true K Chao1 estimate table elements spilled
K = 4,096 4,096 1,749 256 KiB 4,794 (0.05%)
K = 65,536 65,536 3,200 512 KiB 987,037 (9.9%)
K = 262,144 259,002 5,035 1 MiB 1,592,338 (16%)
K = 1M 763,005 6,037 1 MiB 2,637,651 (26%)

Chao1 extrapolates from how many values appear once or twice in the sample. Under Zipf the sample is dominated by a few head values, so the long tail barely shows up. With 1,024 samples the estimate stays under ~6k for every K I tested.

CAFS sizes its fixed table for that estimate. The tail overflows the buckets, and up to a quarter of the array lands on the spill list, which is then sorted with std::sort. The fallback never triggers: it needs more than half the array spilled, and the worst case here is 26%.

A growable hash map doesn’t care how wrong the estimate is. That’s why swapping the table fixes the Zipf rows in the ablation, while everything else in CAFS stays the same.

On uniform data the estimate is fine, but 8 slots per value makes tables large. At K = 262k with uint64 keys it allocates 32 MiB. That fits in this machine’s 260 MiB L3 but not in the 18 MiB L3 of the paper’s i5. I didn’t test how much that matters there.

What it means

If a column has fewer than ~10 distinct values, CAFS’s unrolled path is a real trick and worth stealing. It’s 30 lines, and a hash map can’t match it.

From there up to tens of thousands of distinct values, the speedup over general sorts comes from counting. For 64-bit keys, a good hash map and a fill_n already get it. Two things add to that: merging runs of equal neighbors before the table, if your data arrives clustered, and, for 32-bit keys, CAFS’s bucket.

Past that, check your skew. A table sized once from a sample is a bet that the sample saw the distribution. Zipf-like data, which describes a lot of real columns, loses that bet.

Limits of this experiment:

Reproduce it

Everything is in /code/cafs-is-counting/, also as one tarball. That covers the benchmark (bench.cpp), the ablation (ablate.cpp), the diagnostic (diag.cpp), the scripts, the raw CSVs and the vendored headers (CAFS, pdqsort, ska_sort, unordered_dense), so nothing needs downloading.

./run.sh               # full grid + ablation, ~45 min on 1 core
python3 analyze.py 64  # median tables (or 32)
python3 plot.py        # figures (needs matplotlib)

The Zipf result alone takes 10 seconds:

g++ -O3 -march=x86-64-v3 -std=c++20 -DNDEBUG -o ablate ablate.cpp
./ablate zipf 10000000 5 65536   # columns: dist,N,K,algo,rep,ns_per_elem,ok,key_bits