Skip to content

Instantly share code, notes, and snippets.

@nitishfy
Last active January 2, 2025 14:34
Show Gist options
  • Save nitishfy/8b883f57597eb76929462355ddcd17fd to your computer and use it in GitHub Desktop.
Save nitishfy/8b883f57597eb76929462355ddcd17fd to your computer and use it in GitHub Desktop.
Benchmarking
package main
import (
"fmt"
"strings"
"testing"
)
// generateArgs generates args (100)
func generateArgs() []string {
var args []string
for i := 0; i < 100; i++ {
val := fmt.Sprintf("value-%d", i)
args = append(args, val)
}
return args
}
// BenchmarkEchoEfficient provides a benchmark for the echo command logic written in an efficient manner
func BenchmarkEchoEfficient(b *testing.B) {
args := generateArgs()
for i := 0; i < b.N; i++ {
_ = strings.Join(args[1:], " ")
}
}
// BenchmarkEchoInefficient provides a benchmark for the echo command logic written in an inefficient manner
func BenchmarkEchoInefficient(b *testing.B) {
args := generateArgs()
for i := 0; i < b.N; i++ {
var s, sep string
for _, arg := range args {
s += sep + arg
sep = " "
}
}
}
// Run the benchmark: go test -bench=.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment