Created
April 8, 2025 15:26
-
-
Save cnnrrss/5f14aea08d163c8e0404ec9d3551697c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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