Last active
January 2, 2025 14:34
-
-
Save nitishfy/8b883f57597eb76929462355ddcd17fd to your computer and use it in GitHub Desktop.
Benchmarking
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" | |
"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