go / intermediate
Snippet
Measuring Execution Speed and Memory Allocations with Benchmarks
Go provides first-class benchmarking utilities via the testing package. Benchmark functions must begin with 'Benchmark' and accept '*testing.B'. Calling 'ReportAllocs()' prints memory allocation statistics (bytes/op and allocs/op), which is critical for finding performance bottlenecks.
snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package mainimport ("bytes""testing")func ConcatenateWithBuffer(n int) string {var buf bytes.Bufferfor i := 0; i < n; i++ {buf.WriteString("go")}return buf.String()}func BenchmarkConcatenateWithBuffer(b *testing.B) {b.ReportAllocs()for i := 0; i < b.N; i++ {ConcatenateWithBuffer(1000)}}
Breakdown
1
func BenchmarkConcatenateWithBuffer(b *testing.B) {
Defines a benchmark function. The runner will run this function multiple times with increasing b.N values.
2
b.ReportAllocs()
Instructs the benchmark tool to measure and print memory allocations for the runs.
3
for i := 0; i < b.N; i++ {
Executes the code block under test b.N times, which is dynamically adjusted to get a stable execution time.