diff --git a/internal/util.go b/internal/util.go index cc1bff24e..f77775ff4 100644 --- a/internal/util.go +++ b/internal/util.go @@ -49,22 +49,7 @@ func isLower(s string) bool { } func ReplaceSpaces(s string) string { - // Pre-allocate a builder with the same length as s to minimize allocations. - // This is a basic optimization; adjust the initial size based on your use case. - var builder strings.Builder - builder.Grow(len(s)) - - for _, char := range s { - if char == ' ' { - // Replace space with a hyphen. - builder.WriteRune('-') - } else { - // Copy the character as-is. - builder.WriteRune(char) - } - } - - return builder.String() + return strings.ReplaceAll(s, " ", "-") } func GetAddr(addr string) string { diff --git a/internal/util_test.go b/internal/util_test.go index 57f7f9fa1..0bc466466 100644 --- a/internal/util_test.go +++ b/internal/util_test.go @@ -1,6 +1,7 @@ package internal import ( + "runtime" "strings" "testing" @@ -72,3 +73,36 @@ func TestGetAddr(t *testing.T) { Expect(GetAddr("127")).To(Equal("")) }) } + +func BenchmarkReplaceSpaces(b *testing.B) { + version := runtime.Version() + for i := 0; i < b.N; i++ { + _ = ReplaceSpaces(version) + } +} + +func ReplaceSpacesUseBuilder(s string) string { + // Pre-allocate a builder with the same length as s to minimize allocations. + // This is a basic optimization; adjust the initial size based on your use case. + var builder strings.Builder + builder.Grow(len(s)) + + for _, char := range s { + if char == ' ' { + // Replace space with a hyphen. + builder.WriteRune('-') + } else { + // Copy the character as-is. + builder.WriteRune(char) + } + } + + return builder.String() +} + +func BenchmarkReplaceSpacesUseBuilder(b *testing.B) { + version := runtime.Version() + for i := 0; i < b.N; i++ { + _ = ReplaceSpacesUseBuilder(version) + } +}