Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. Go Programming Bootcamp

Lesson 44 of 60 · Go

Writing Benchmarks – `testing.B`

Duration: 15 minutes

Benchmark Example

This lesson explains the main concept clearly with beginner-friendly examples and background so you can learn why the code works.

func BenchmarkEncodeJSON(b *testing.B) {
    obj := map[string]int{"a":1,"b":2,"c":3}
    for i := 0; i < b.N; i++ {
        json.Marshal(obj)
    }
}

Run with:

$ go test -bench=. -benchmem

The output shows ns/op, allocs/op, and B/op.

Controlling benchmark size

func BenchmarkMultiply(b *testing.B) {
    for i := 0; i < b.N; i++ { multiply(12345, 6789) }
}

Use b.ResetTimer() after any preparatory work.

Info

Benchmark only deterministic code; external I/O skews results.

Previous: Performance Tuning – CPU, Memory, and GCNext: Embedding a SQLite Database with `modernc.org/sqlite`