Yesterday, we see the default ns/op metric, which reports how many nanoseconds an operation takes on average. But it is also important to check the allocations. Heap allocations happen when a data is allocated to a heap so that the data remains and survive the function call. Keeping this can put pressure on the garbage collector, thereby affecting CPU usage and latency.
func BenchmarkEncodeJSON(b *testing.B) {
b.ReportAllocs()
for b.Loop() {
if _, err := EncodeJSON(benchmarkEvent); err != nil {
b.Fatal(err)
}
}
}
func BenchmarkEncodeBinary(b *testing.B) {
b.ReportAllocs()
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 7356717 157.2 ns/op 104 B/op 2 allocs/op BenchmarkEncodeBinary-12 40031223 31.24 ns/op 64 B/op 1 allocs/op PASS ok codec01 2.413s