library(tidyverse)
library(arrow)10 Zstandard, LZ4, Snappy and Brotli
10.1 Introduction
The classic compressors were designed when processors were slow and disks were small, so they spent time to save space. By 2010 the balance had shifted. Processors had become so fast, and data so plentiful, that for many jobs the bottleneck was the compressor itself: data arrived from the network or the disk faster than gzip could unpack it. A new generation of codecs was built for that world.
- LZ4, by Yann Collet, open-sourced in 2011, and Snappy, from Google, open-sourced the same year, are LZ77 (Chapter 6) stripped to the bone: byte-aligned tokens and no entropy coding at all. They compress modestly and decompress at gigabytes per second.
- Brotli, by Jyrki Alakuijala and Zoltán Szabadka at Google, first written in 2013 for compressing web fonts and released as a general compressor in 2015 (Alakuijala and Szabadka 2016), adds Huffman coding, context modelling and a built-in dictionary of common text to LZ77. It is the compressor behind much of the web.
- Zstandard, or zstd, also by Yann Collet, released at Facebook in August 2016 and specified in an IETF RFC in 2018, revised in 2021 (Collet and Kucherawy 2021), combines LZ77 with Huffman coding for literal bytes and a fast form of asymmetric numeral systems (Duda 2013) for everything else. Its levels run from blisteringly fast to nearly as tight as xz, and its decompression is fast at every level.
All four are open source and documented, and Zstandard and Brotli are specified in RFCs published by the Internet Engineering Task Force. This chapter measures them against the classics on the same data and ends with advice on choosing.
Prerequisites
arrow can compress a stream of bytes with any codec it was built with. codec_is_available() says which those are on your machine:
c("lz4_frame", "snappy", "zstd", "brotli", "gzip", "bz2") |>
set_names() |>
map_lgl(codec_is_available)
#> lz4_frame snappy zstd brotli gzip bz2
#> TRUE TRUE TRUE TRUE TRUE TRUE10.2 A fair race
To compare codecs fairly, compress the same bytes with each and measure three things: the compression ratio, and the speed of compressing and of decompressing, in megabytes of original data per second. The test data is the dimuon CSV text, about 7 MB:
csv_bytes <- memDecompress(
readBin("data/dimuon.csv.gz", "raw", file.size("data/dimuon.csv.gz")),
type = "gzip"
)
length(csv_bytes) / 1e6
#> [1] 6.869021arrow compresses through streams: a CompressedOutputStream wraps another stream and compresses whatever is written to it. Writing into a BufferOutputStream keeps everything in memory, so the timings measure the codec rather than the disk:
compress_with <- function(bytes, codec, level = NA) {
sink <- BufferOutputStream$create()
stream <- CompressedOutputStream$create(sink, codec = codec, compression_level = level)
stream$write(bytes)
stream$close()
sink$finish()
}
decompress_with <- function(buffer, codec, n_bytes) {
stream <- CompressedInputStream$create(BufferReader$create(buffer), codec = codec)
out <- stream$Read(n_bytes + 1)
stream$close()
out
}
packed <- compress_with(csv_bytes, "zstd", level = 3)
identical(as.raw(decompress_with(packed, "zstd", length(csv_bytes))), csv_bytes)
#> [1] TRUEThe fastest codecs finish in a few milliseconds, too quickly for a single measurement to mean much, so this helper repeats a job until at least half a second has passed and reports the average time per run:
seconds_per_run <- function(job, min_seconds = 0.5) {
runs <- 0
start <- proc.time()[["elapsed"]]
repeat {
job()
runs <- runs + 1
elapsed <- proc.time()[["elapsed"]] - start
if (elapsed >= min_seconds) return(elapsed / runs)
}
}Now the race. Each codec runs at a few of its levels; NA means the codec’s default:
contestants <- tribble(
~codec, ~level,
"lz4_frame", NA,
"zstd", 1,
"zstd", 3,
"zstd", 9,
"zstd", 19,
"brotli", 1,
"brotli", 5,
"brotli", 11,
"gzip", 1,
"gzip", 6,
"gzip", 9,
"bz2", NA
)
race <- contestants |>
mutate(
packed = map2(codec, level, \(c, l) compress_with(csv_bytes, c, l)),
ratio = length(csv_bytes) / map_dbl(packed, \(p) p$size),
compress_s = map2_dbl(codec, level, \(c, l) seconds_per_run(\() compress_with(csv_bytes, c, l))),
decompress_s = map2_dbl(packed, codec, \(p, c) seconds_per_run(\() decompress_with(p, c, length(csv_bytes))))
) |>
select(!packed)arrow has no xz codec, so xz joins through base R’s memCompress(), which uses xz -9e:
xz_packed <- memCompress(csv_bytes, type = "xz")
race <- race |>
add_row(
codec = "xz",
level = 9,
ratio = length(csv_bytes) / length(xz_packed),
compress_s = seconds_per_run(\() memCompress(csv_bytes, type = "xz")),
decompress_s = seconds_per_run(\() memDecompress(xz_packed, type = "xz"))
)
race <- race |>
mutate(
label = if_else(is.na(level), codec, paste0(codec, "-", level)),
compress_mb_s = length(csv_bytes) / 1e6 / compress_s,
decompress_mb_s = length(csv_bytes) / 1e6 / decompress_s
)
race |>
select(label, ratio, compress_mb_s, decompress_mb_s) |>
arrange(desc(ratio))
#> # A tibble: 13 × 4
#> label ratio compress_mb_s decompress_mb_s
#> <chr> <dbl> <dbl> <dbl>
#> 1 bz2 3.29 12.7 13.9
#> 2 xz-9 3.21 1.04 42.3
#> 3 brotli-11 3.10 0.518 189.
#> 4 zstd-19 3.10 1.55 370.
#> 5 zstd-9 2.75 25.9 467.
#> 6 gzip-9 2.73 4.02 261.
#> 7 gzip-6 2.71 9.41 261.
#> 8 brotli-5 2.70 27.5 234.
#> 9 zstd-1 2.57 291. 591.
#> 10 zstd-3 2.51 154. 398.
#> 11 brotli-1 2.50 121. 220.
#> 12 gzip-1 2.31 79.3 247.
#> 13 lz4_frame 1.61 302. 637.A table of thirteen rows is hard to read. The same numbers are clearer as three panels side by side, one row per contestant, sorted by compression ratio:
race |>
mutate(label = fct_reorder(label, ratio)) |>
pivot_longer(
c(ratio, compress_mb_s, decompress_mb_s),
names_to = "measure",
values_to = "value"
) |>
mutate(
measure = factor(
measure,
levels = c("ratio", "compress_mb_s", "decompress_mb_s"),
labels = c("Compression ratio", "Compressing (MB/s)", "Decompressing (MB/s)")
)
) |>
ggplot(aes(x = value, y = label, colour = codec)) +
geom_point(size = 2.4) +
scale_x_log10(labels = scales::label_number(accuracy = 0.1, drop0trailing = TRUE)) +
facet_wrap(~measure, scales = "free_x") +
labs(x = NULL, y = NULL, colour = "Codec") +
theme(panel.grid.major.y = element_line(colour = "grey92"))
Read the first two panels together. Compression is a trade: every codec can buy ratio with time by searching harder, and the range runs from LZ4, fast and loose, at one end, to bzip2, xz and the top levels of Zstandard and Brotli, tight and slow, at the other. gzip sits in the middle, and the modern codecs beat it on both counts at once. Zstandard at level 9 compresses slightly better than gzip at level 9 and about 6 times faster; at level 1 it gives up a few percent of gzip’s default ratio and compresses about 31 times faster.
The third panel is the real story. Decompression speed barely depends on the level for Zstandard, so a file squeezed with zstd-19, slowly and once, unpacks about as fast as one written with zstd-1. LZ4 and Zstandard decompress two to four times faster than gzip here, and ten to thirty times faster than bzip2 and xz. Data is usually written once and read many times, so this is the speed that matters most.
One caution about the test. This text compresses well because CSV is full of repeated punctuation and digits. Binary floating-point measurements often compress much less, because, as Chapter 4 showed, their trailing bits are noise; the dimuon kinematics stored as doubles shrink by only about a quarter (Chapter 13). The ranking of the codecs changes little; the ratios do.
10.3 Snappy and LZ4 live inside formats
Snappy’s raw format has no streaming container, which is why it was missing from the race. You will almost never use Snappy or LZ4 directly. They live inside file formats, compressing each piece of a file separately so that any piece can be read on its own. arrow’s write_parquet() uses Snappy by default (Chapter 13), and write_ipc_file(), which writes the Arrow IPC format also known as Feather, uses LZ4 by default (Chapter 14). Big-data systems chose them for the right panel of the figure: when a query reads gigabytes, decompression has to keep up with the disk.
10.4 Zstandard in R
Zstandard is the codec to learn if you learn only one new one. R has it in three places:
- Base R, since version 4.5, if R was built with zstd support, as the CRAN builds for Windows are:
memCompress(x, "zstd"), azstdfile()connection for.zstfiles, andsaveRDS(x, file, compress = "zstd"). - arrow:
write_parquet(x, path, compression = "zstd", compression_level = 9),write_ipc_file(x, path, compression = "zstd"), and the stream classes used above. - duckdb, which compresses its own database files and writes Parquet with zstd on request (Chapter 15).
extSoftVersion() reports which compression libraries your R was built with:
extSoftVersion()[c("zlib", "bzlib", "xz", "zstd", "libdeflate")]
#> zlib bzlib xz
#> "1.3.1" "1.0.8, 13-Jul-2019" "5.8.2"
#> zstd libdeflate
#> "1.5.7" "1.25"Zstandard’s levels deserve a second look. Levels 1 to 19 are the normal range, with 3 the default, and levels up to 22 are available to command-line users who ask for them. Negative levels trade ratio for still more speed. And Zstandard can train a dictionary on a sample of small, similar files, then use it to compress each new one; for many small records of the same shape, such as one file per event or per sensor reading, that can make a large difference.
10.5 Choosing a codec
There is no best codec, only a best codec for a job. This table sums up the chapter, and the figure above is the evidence for it:
| Job | Choose | Why |
|---|---|---|
| Files to share or archive for decades, read by any tool | gzip | Universal since the early 1990s, and certain to stay readable |
| Analysis files you read again and again | zstd, low to middle level | Good ratio, and decompression at gigabytes per second |
| Data written as fast as it is produced, scratch files | LZ4 or zstd at level 1 | Fastest to write, still fast to read |
| Data written once and distributed widely | zstd at a high level, or xz | Smallest files; zstd also reads back much faster |
| Text served on the web | Brotli or zstd | What browsers and servers expect |
| Inside Parquet and Arrow files | zstd, or the defaults Snappy and LZ4 | Each column chunk compressed on its own |
Whichever you choose, remember the lesson of Chapter 4: the biggest gains come before the codec, from storing integers instead of doubles, differences instead of values, and the precision you measured instead of the precision your computer offers.
10.6 Summary
LZ4 and Snappy strip LZ77 down for speed, Brotli and Zstandard add modern entropy coding to it, and all four are open, documented and widely implemented. You raced them against gzip, bzip2 and xz on the same data, with arrow’s compressed streams and base R’s memCompress(), and found that compression speed trades against ratio while Zstandard and LZ4 decompress fast at every setting. Zstandard is in base R since version 4.5, in arrow and in duckdb, and for most new work it is the codec to choose, with gzip kept for files that must open anywhere.
10.7 Exercises
- Run the race on binary data instead of text: the magnetometer’s
bx_ntcolumn as doubles,writeBin(bx, raw()). How do the ratios change? Does the ranking of the codecs change? - Repeat it on the same column as integer differences in units of 0.01 nT, as in Chapter 4. Which codec benefits most from the better representation?
- Add zstd levels -5, 6, 12 and 15 to the race, and plot ratio against compression speed for zstd alone. Where would you put the default if you were choosing it?
- Write the dimuon table with
write_ipc_file()usingcompression = "lz4","zstd"and"uncompressed". Compare the file sizes and the timeread_ipc_file()takes for each. - Use
zstdfile()to write the magnetometer CSV text to a.csv.zstfile, then read it back withread_csv(zstdfile(path)). Compare its size with the.csv.gzoriginal.