mirror of
https://github.com/redis/go-redis.git
synced 2025-06-05 06:42:39 +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 {
|
||||
// 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 {
|
||||
|
@ -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)
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user