File tree Expand file tree Collapse file tree 2 files changed +35
-16
lines changed
Expand file tree Collapse file tree 2 files changed +35
-16
lines changed Original file line number Diff line number Diff line change @@ -49,22 +49,7 @@ func isLower(s string) bool {
4949}
5050
5151func 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
7055func GetAddr (addr string ) string {
Original file line number Diff line number Diff line change 11package internal
22
33import (
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+ }
You can’t perform that action at this time.
0 commit comments