Skip to content

Commit 3af2cc5

Browse files
authored
chore: optimize function ReplaceSpaces (#3383)
* chore: optimize function `ReplaceSpaces` Signed-off-by: fukua95 <[email protected]> * trigger CI again because the bug of docker Signed-off-by: fukua95 <[email protected]> * trigger CI again because the bug of docker Signed-off-by: fukua95 <[email protected]> --------- Signed-off-by: fukua95 <[email protected]>
1 parent 43e7fb5 commit 3af2cc5

File tree

2 files changed

+35
-16
lines changed

2 files changed

+35
-16
lines changed

internal/util.go

Lines changed: 1 addition & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -49,22 +49,7 @@ func isLower(s string) bool {
4949
}
5050

5151
func ReplaceSpaces(s string) string {
52-
// Pre-allocate a builder with the same length as s to minimize allocations.
53-
// This is a basic optimization; adjust the initial size based on your use case.
54-
var builder strings.Builder
55-
builder.Grow(len(s))
56-
57-
for _, char := range s {
58-
if char == ' ' {
59-
// Replace space with a hyphen.
60-
builder.WriteRune('-')
61-
} else {
62-
// Copy the character as-is.
63-
builder.WriteRune(char)
64-
}
65-
}
66-
67-
return builder.String()
52+
return strings.ReplaceAll(s, " ", "-")
6853
}
6954

7055
func GetAddr(addr string) string {

internal/util_test.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package internal
22

33
import (
4+
"runtime"
45
"strings"
56
"testing"
67

@@ -72,3 +73,36 @@ func TestGetAddr(t *testing.T) {
7273
Expect(GetAddr("127")).To(Equal(""))
7374
})
7475
}
76+
77+
func BenchmarkReplaceSpaces(b *testing.B) {
78+
version := runtime.Version()
79+
for i := 0; i < b.N; i++ {
80+
_ = ReplaceSpaces(version)
81+
}
82+
}
83+
84+
func ReplaceSpacesUseBuilder(s string) string {
85+
// Pre-allocate a builder with the same length as s to minimize allocations.
86+
// This is a basic optimization; adjust the initial size based on your use case.
87+
var builder strings.Builder
88+
builder.Grow(len(s))
89+
90+
for _, char := range s {
91+
if char == ' ' {
92+
// Replace space with a hyphen.
93+
builder.WriteRune('-')
94+
} else {
95+
// Copy the character as-is.
96+
builder.WriteRune(char)
97+
}
98+
}
99+
100+
return builder.String()
101+
}
102+
103+
func BenchmarkReplaceSpacesUseBuilder(b *testing.B) {
104+
version := runtime.Version()
105+
for i := 0; i < b.N; i++ {
106+
_ = ReplaceSpacesUseBuilder(version)
107+
}
108+
}

0 commit comments

Comments
 (0)