We learned from the previous daily entries that serializing a struct can be done via the json package or manual binary serialization. There are other ways, but we will just focus on these two. To help us with determining which one to use, we can check performance metrics.
In Go, we can use benchmark tests to measure a specific process, like EncodeJSON.
func EncodeJSON(event Event) ([]byte, error) {
return json.Marshal(event)
}
A test with Benchmark prefix is how a benchmark test is discovered. The test below isolates EncodeJSON because we want to single it out.
var benchmarkEvent = Event{
ID: 42,
Message: "This message is the workload used by both codecs.",
}
func BenchmarkEncodeJSON(b *testing.B) {
for b.Loop() { // dictates iteration count and the timing; we're handing the control over the execution to Go's benchmark runner
if _, err := EncodeJSON(benchmarkEvent); err != nil {
b.Fatal(err)
}
}
}
We run the benchmark test with the command below. By default, go test discovers all normal test functions, so we use ^$ to include blank tests, effectively skipping the existing tests; however, we have -bench that selects the specific benchmark name.
go test -run '^$' -bench '^BenchmarkEncodeJSON$'
goos: linux
goarch: arm64
pkg: codec01
BenchmarkEncodeJSON-12 8042766 149.1 ns/op
PASS
ok codec01 1.203s
The output says it performed 8042766 encoding operations and each JSON encoding took approximately 149.1 nanoseconds on average.