Skip to content

chore: optimize function ReplaceSpaces #3383

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
May 19, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 1 addition & 16 deletions internal/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
34 changes: 34 additions & 0 deletions internal/util_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package internal

import (
"runtime"
"strings"
"testing"

Expand Down Expand Up @@ -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)
}
}
Loading