Skip to content

Instantly share code, notes, and snippets.

@cnnrrss
Created April 8, 2025 15:26
Show Gist options
  • Save cnnrrss/5f14aea08d163c8e0404ec9d3551697c to your computer and use it in GitHub Desktop.
Save cnnrrss/5f14aea08d163c8e0404ec9d3551697c to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"math/rand"
"strings"
"testing"
)
var (
a string
b string
)
func init() {
a = randomString(10)
b = randomString(10)
}
func main() {
result := testing.Benchmark(BenchmarkSprintf)
fmt.Printf("%-20s\t%s\n", "BenchmarkSprintf", result)
result = testing.Benchmark(BenchmarkStringsJoin)
fmt.Printf("%-20s\t%s\n", "BenchmarkStringsJoin", result)
/**
Prints...
BenchmarkSprintf 16642424 70.95 ns/op
BenchmarkStringsJoin 53095192 22.19 ns/op
*/
}
func BenchmarkSprintf(bm *testing.B) {
for i := 0; i < bm.N; i++ {
_ = fmt.Sprintf("%s:%s", a, b)
}
}
func BenchmarkStringsJoin(bm *testing.B) {
for i := 0; i < bm.N; i++ {
_ = strings.Join([]string{a, b}, ":")
}
}
// Helper to generate a random string of length n
func randomString(n int) string {
letters := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
b := make([]rune, n)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment