mirror of
https://github.com/redis/go-redis.git
synced 2025-06-06 17:40:59 +03:00
chore: optimize function ReplaceSpaces
(#3383)
* chore: optimize function `ReplaceSpaces` Signed-off-by: fukua95 <fukua95@gmail.com> * trigger CI again because the bug of docker Signed-off-by: fukua95 <fukua95@gmail.com> * trigger CI again because the bug of docker Signed-off-by: fukua95 <fukua95@gmail.com> --------- Signed-off-by: fukua95 <fukua95@gmail.com>
This commit is contained in:
parent
43e7fb5eef
commit
3af2cc5783
@ -49,22 +49,7 @@ func isLower(s string) bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func ReplaceSpaces(s string) string {
|
func ReplaceSpaces(s string) string {
|
||||||
// Pre-allocate a builder with the same length as s to minimize allocations.
|
return strings.ReplaceAll(s, " ", "-")
|
||||||
// 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 GetAddr(addr string) string {
|
func GetAddr(addr string) string {
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
package internal
|
package internal
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"runtime"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
@ -72,3 +73,36 @@ func TestGetAddr(t *testing.T) {
|
|||||||
Expect(GetAddr("127")).To(Equal(""))
|
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…
x
Reference in New Issue
Block a user