skip to content
Alvin Lucillo

Benchmark encoding throughput

/ 1 min read

To measure encoding throughput, we set the number of bytes processed per single operation. In the code below, that will be the length of the message. As we can see in the result, JSON encoding processes approximately 281.23 MB/s and binary encoding approximately 1555.57 MB/s. This means based on the benchmark binary encoding can process more data per second.

func BenchmarkEncodeJSON(b *testing.B) {
	b.ReportAllocs()
	b.SetBytes(int64(len(benchmarkEvent.Message)))

	for b.Loop() {
		if _, err := EncodeJSON(benchmarkEvent); err != nil {
			b.Fatal(err)
		}
	}
}

func BenchmarkEncodeBinary(b *testing.B) {
	b.ReportAllocs()
	b.SetBytes(int64(len(benchmarkEvent.Message)))

	for b.Loop() {
		_ = EncodeBinary(benchmarkEvent)
	}
}

In the result below, we can see that binary encoding uses less allocation resources. Binary encoding uses less bytes and less number of allocation per event.

go test -run '^$' -bench '^BenchmarkEncode'
goos: linux
goarch: arm64
pkg: codec01
BenchmarkEncodeJSON-12           6235954               174.2 ns/op       281.23 MB/s         104 B/op          2 allocs/op
BenchmarkEncodeBinary-12        35892894                31.50 ns/op     1555.57 MB/s          64 B/op          1 allocs/op
PASS
ok      codec01 2.224s