One of the great tools Go offers is a benchmarking command. Writing benchmarks to compare the allocation of memory and the execution time is extremely simple—it’s very similar to writing a test over a function.
We’ll use the type B
, defined in the testing
package (you’ll never guess what B
stands for). The type B
has one exposed field and an integer N
, which counts the number of iterations the benchmark has executed. When running benchmarks, this field has an initial value that will allow at least a certain number of iterations to ensure that we have a steady result—no need to try and set it manually. Test benchmarking functions follow a convention very similar to test functions: their name must start with Benchmark
.
In section 5.2.1 of chapter 5, we explained that using concatenation to build long strings isn’t a good idea, and you should use a builder. Don’t take our word for it; measure it yourself!
We’re building a string that represents the feedback
type, which is a slice
of status
es. The following listing shows the necessary code.
Listing D.1 status_internal_test.go
: Examples of benchmarks
// Benchmark the string concatenation with only one value in feedback func BenchmarkStringConcat1(b *testing.B) { fb := feedback{absentCharacter} for n := 0; n < b.N; n++ { #1 _ = fb.StringConcat() } }