Hacker News

Variable-Length Integers in Go

Comments

I've run into variable-length integers a few times recently, first when benchmarking Protobuf varints against fixed-width integers and again while implementing QUIC's framing for HTTP/3 From Scratch.

Comparing those two encodings is what pushed me to design a different varint strategy for OmniBuf. I ended up benchmarking six different integer encodings in Go. I was originally interested in the tradeoff between CPU time and wire size, but some of the results were pretty unexpected. For example, sorting the input before encoding it made some of the decoders run three times as fast.

Why Variable-Length Integers?

Soโ€ฆ why do we want to use variable-length integers, anyway? Let's use the number 300. In binary, 300 is 1 0010 1100 (9 bits).

Send it over the wire as a big-endian, fixed-width 64-bit unsigned integer (uint64), and those bits look like this: 00000000 00000000 00000000 00000000 00000000 00000000 00000001 00101100

That's 55 bits of nothing. If we're encoding something like a Protobuf field number or an array length, we probably don't need anywhere near 64 bits.

We could remove those leading zeros, but then how would we encode two integers next to each other? If I write out the bits for 300 immediately followed by the bits for 5, there's no way to recover those two numbers unless we know their lengths, which naively, would be another number we have to encode!

The good news is that there are quite a few ways to solve this and we're going to cover a few of the popular ones.

Six Integer Encodings

Protobuf / LEB128

Protobuf uses LEB128 (Little-Endian Base 128). Read a byte, take the bottom 7 bits, and check the top bit (the continuation bit). If it's set, read another byte and place its bottom 7 bits above the previous ones. Repeat until you get a byte where the top bit is zero.

There are already two implementations of this in Go that we can benchmark: encoding/binary.Uvarint in the standard library and protowire.ConsumeVarint in the Protobuf library. The Protobuf implementation unrolls the decoding loop, while the standard library uses a regular loop.

I also wrote my own version (LEB128 (fast1B) in the benchmarks below) that handles single-byte integers in the outer loop, which appears to be a bit more efficient in many cases:

func DecodeLEB128(src []byte, dst []uint64) int {
  i, n := 0, 0
  for i < len(src) {
    // ...
  }
  return n
}

QUIC

What I like about this encoding is that we know exactly how many bytes to read after looking at the first byte. We can also use the functions in encoding/binary to read the remaining bits in one go.

With this encoding, we can't store anything larger than 2^62 - 1. That's fine for HTTP/3 frame lengths, but I wanted OmniBuf to support the entire uint64 range.

Also, this is big endian byte ordering AKA network ordering. Almost all modern processors use little-endian byte ordering. Google actually used little endian byte ordering in the original versions of QUIC (aka gQUIC) and it was switched to big endian when being adopted as a standard by the IETF. Honestly, this alone is an interesting story and worthy of a full article. But that will wait for another time.

OmniBuf

For OmniBuf, I wanted something like QUIC's varints that still kept the full 64-bit range and could fit 127 in a single byte. I also wanted little-endian byte order to avoid byte swapping most CPUs. I went with a variation of prefix varints, similar to Rust's vint64 and LLVM's MLIR bytecode varints.

Instead of QUIC's top two bits, we count the trailing zeros at the bottom of the first byte. Since the integer is little-endian, keeping the tag in the low bits leaves all the payload bits contiguous so we can strip it with a single right shift:

  • ...1 (0 trailing zeros): 1 byte, 7 payload bits (0..127)
  • ...10 (1 trailing zero): 2 bytes, 14 payload bits (0..16,383)
  • ...100 (2 trailing zeros): 4 bytes, 29 payload bits (0..536,870,911)
  • 0x00: 9 bytes, followed by a raw 8-byte little-endian uint64
func DecodeOmniBuf(src []byte, dst []uint64) int {
  i, n := 0, 0
  for i < len(src) {
    // ...
  }
  return n
}

By limiting the encoded widths to 1, 2, 4, and 9 bytes, we can extract each payload with a single uint8, uint16, uint32, or uint64 read. Anything at 2^29 or above takes nine bytes, even when LEB128 would only use five.

Prefix-9

What if we didn't skip those other widths? Each additional trailing zero in the first byte indicates another byte of encoded data: zero trailing zeros for 1 byte, one for 2 bytes, two for 3 bytes, and so on up to 9 bytes. (That also means OmniBuf's 4-byte encoding gets 29 payload bits, one more than Prefix-9's 28.)

I'll call this encoding Prefix-9 throughout the benchmarks. It takes the same number of bytes as LEB128 for integers up to 56 bits. Anything larger gets a zero byte followed by a uint64, so we never need that tenth byte that LEB128 sometimes uses.

For values up to 16,383 (including 300), Prefix-9 produces the exact same bytes as OmniBuf. Switching to 70,000 shows the 3-byte case that OmniBuf skips:

There's a neat trick we can do with this format. Since the number of trailing zeros tells us both the length of the integer and how many bits we need to remove, we can decode the first eight widths with no switch statement. Read eight bytes and shift the bits we don't want off either end:

tz := uint(bits.TrailingZeros8(b0))
width := tz + 1
word := binary.LittleEndian.Uint64(src[i:])
shiftLeft := (8 - width) * 8
dst[n] = (word << shiftLeft) >> (shiftLeft + width)
i += int(width)

In the full decoder, we check for the 0x00 9-byte escape first and fall back to a byte-by-byte loop when fewer than eight bytes remain. I also wanted to see how much we'd gain by special-casing small integers again. Prefix-9 (fast1B) is the same decoder with an extra if b0&1 != 0 check before it does any of this work.

MessagePack

MessagePack (MsgPack) is a self-describing format where the first byte encodes the value's type (and, for small integers, the value itself). Values from 0 to 127 just use 0x00 through 0x7f directly, so they don't need a separate tag byte. To encode 300 as an unsigned integer, we first write 0xcd (the uint16 type) and then write the two bytes of the integer in big-endian order.

b0 := src[i]
if b0 <= 127 {
  dst[n] = uint64(b0)
  i++
} else {
  switch b0 {
  case 0xcc:
    dst[n] = uint64(src[i+1])
    i += 2
  case 0xcd:
    dst[n] = uint64(binary.BigEndian.Uint16(src[i+1:]))
    i += 3
  case 0xce:
    dst[n] = uint64(binary.BigEndian.Uint32(src[i+1:]))
    i += 5
  case 0xcf:
    dst[n] = binary.BigEndian.Uint64(src[i+1:])
    i += 9
  }
}

The switch here looks a lot like the one for QUIC, except we're spending a whole byte on the type rather than a couple of bits from the integer.

Fixed64

I also want to have a baseline for all of these benchmarks where we just write out the eight bytes of each uint64 in little-endian order.

There's an interesting opportunity to cheat a bit here. On a little-endian machine, the bytes we want to write are already laid out correctly in memory. We can use unsafe.Slice to treat our integers as a slice of bytes and just call copy. I'll benchmark both that version (Fixed64 Unsafe) and a regular Go loop (Fixed64).

func DecodeFixed64(src []byte, dst []uint64) int {
  n := len(src) / 8
  dst = dst[:n]
  for j := range dst {
    dst[j] = binary.LittleEndian.Uint64(src[:8])
    src = src[8:]
  }
  return n
}

func DecodeFixed64Unsafe(src []byte, dst []uint64) int {
  n := len(src) / 8
  if n == 0 {
    return 0
  }
  dst = dst[:n]
  out := unsafe.Slice((*byte)(unsafe.Pointer(unsafe.SliceData(dst))), n*8)
  copy(out, src[:n*8])
  return n
}

I originally wrote that loop with src[j*8:], but reslicing with src[:8] and src = src[8:] lets the Go compiler drop a bounds check inside binary.LittleEndian.Uint64. That one change made Fixed64 noticeably faster.

Other Schemes

There are a few other varint encodings that I didn't benchmark.

Group Varint (Varint-GB) encodes four integers together. The first byte contains four 2-bit lengths, so we can figure out where all four integers are before we read any of them. This is particularly useful for decoding arrays with SIMD instructions like pshufb or tbl. It doesn't fit quite as nicely into formats where we're encoding one integer at a time.

CBOR is similar to MessagePack, except its first byte packs a 3-bit major type with a 5-bit value. Anything from 0 to 23 lives right in those 5 bits, and values 24 through 27 mean a 1, 2, 4, or 8-byte integer follows.

SQLite4 went a different route: its varints sort in the same order whether you compare the raw bytes or the decoded unsigned integers, which is handy for database indexes.

Format Summary

Format Widths (B) Endian 1-Byte Max
LEB128 1-10 LE 0..127 64-bit
QUIC 1, 2, 4, 8 BE 0..63 62-bit
OmniBuf 1, 2, 4, 9 LE 0..127 64-bit
Prefix-9 1-9 LE 0..127 64-bit
MessagePack 1, 2, 3, 5, 9 BE 0..127 64-bit
Fixed64 8 LE None 64-bit

Benchmark Setup

All of these benchmarks run on my M1 Pro MacBook with Go 1.27.4 (-count=3 -benchtime=250ms), and the numbers below are the means across those three runs. Each benchmark processes 10,000 integers at a time and reuses buffers small enough to stay in CPU cache.

My hand-rolled decoders also cheat a bit. They assume the input is valid and the output slice is already large enough, so they skip the bounds and error checks that encoding/binary and protowire have to run on every call.

I generated six datasets of 10,000 integers each:

Dataset Values
Small Random integers from 0 to 63
Large Random 41-bit integers around 2^40
FullWidth Uniformly distributed random uint64 values
Skewed 70% small, 20% medium, 8% big, 2% huge (shuffled)
MixedRandom 25% of each of the four sizes, shuffled
MixedSorted The same integers as MixedRandom, sorted

For Skewed and the two mixed datasets, I'm using these ranges:

Bucket Range
Small 0..127
Medium 128..16,127
Big 65,536..100M
Huge Around 2^40

I used 63 as the upper limit for Small so that even QUIC can encode everything in one byte. I've left QUIC out of the FullWidth benchmarks because it can't encode the entire uint64 range.

Wire Size

Here is the encoded byte count for 10,000 uint64 values across each dataset:

Show wire size table

Codec Small Large (2^40) FullWidth Skewed Mixed
LEB128 10,000 B 60,000 B 94,988 B 15,386 B 32,706 B
Prefix-9 10,000 B 60,000 B 89,967 B 15,386 B 32,706 B
OmniBuf 10,000 B 90,000 B 90,000 B 16,009 B 40,491 B
MsgPack 10,000 B 90,000 B 90,000 B 18,812 B 45,440 B
QUIC 10,000 B 80,000 B N/A 19,266 B 39,135 B
Fixed64 80,000 B 80,000 B 80,000 B 80,000 B 80,000 B

The Skewed dataset is roughly what I had in mind when designing OmniBuf's varints. I gave up five of Prefix-9's possible byte widths, and it only cost me about 4% in this dataset. That decision looks considerably worse on Large. OmniBuf needs nine bytes for every integer, while LEB128 and Prefix-9 only need six.

There's also not much point in using a varint for something like a random 64-bit hash. On FullWidth, all of these varint formats make the data bigger than it was to begin with.

Decode Speed

Show full decode table (ns/op for 10,000 values; Skewed ns/int is the average time per integer)

Codec Small Large FullWidth Skewed Skewed (ns/int) MixedRandom MixedSorted
Fixed64 Unsafe 920 947 932 927 0.09 925 916
Fixed64 7,459 7,428 8,139 7,501 0.75 7,491 7,511
OmniBuf 6,305 15,651 15,729 9,465 0.95 21,589 10,706
MsgPack 6,264 15,712 15,629 10,365 1.04 25,216 11,946
LEB128 (fast1B) 6,335 32,862 79,249 10,582 1.06 36,932 18,881
QUIC 8,456 9,444 N/A 12,537 1.25 34,263 9,704
Prefix-9 (fast1B) 6,340 28,143 8,288 15,960 1.60 30,635 22,789
Prefix-9 28,638 28,552 7,187 28,824 2.88 29,969 28,673
LEB128 (stdlib) 13,359 43,897 98,850 33,448 3.34 63,278 26,983
LEB128 (protowire) 20,969 29,969 65,361 40,911 4.09 60,815 25,045

On Small, every hand-rolled decoder with a 1-byte fast path takes around 6.3 ยตs: MsgPack, OmniBuf, LEB128 (fast1B), and Prefix-9 (fast1B). Neither library implementation matches the hand-rolled fast path on Small; function-call overhead and input validation are likely contributors.

On FullWidth, protowire's unrolling beats both other LEB128 decoders, but it is still over 4x slower than OmniBuf and about 9x slower than Prefix-9. Prefix-9 has an advantage here because it checks for the 9-byte escape first, while OmniBuf has to check the other three widths before reaching that case.

I should point out the scale of these numbers. The difference between OmniBuf and LEB128 (protowire) on Skewed works out to about three nanoseconds per integer. If your Protobuf message has five integer fields, you probably have more important things to optimize.

Encode Speed

Show full encode table (ns/op)

| Codec | Small | Large | FullWidth | Skewed | MixedRandom | MixedSorted |
|---|---|---|---|---|---|---|
| Fixed64 Unsafe | 1,027 | 955 | 1,048 | 1,046 | 918 | 955 |
| Fixed64 | 3,977 | 4,364 | 3,956 | 4,283 | 3,932 | 3,994 |
| OmniBuf | 6,398 | 18,769 | 18,763 | 14,595 | 32,179 | 11,990 |
| QUIC | 6,322 | 15,646 | N/A | 18,125 | 30,974 | 11,890 |
| LEB128 (fast1B) |

Read on Hacker News ↗ ← Back to News

Comments

No comments yet. Start the discussion.