]> Cypherpunks repositories - gostls13.git/commitdiff
strings: optimize Replace by using a strings.Builder
authorPolina Osadcha <polliosa@google.com>
Thu, 18 Jun 2020 13:17:13 +0000 (16:17 +0300)
committerMartin Möhrmann <moehrmann@google.com>
Mon, 17 Aug 2020 04:08:35 +0000 (04:08 +0000)
name        old time/op    new time/op    delta
ReplaceAll     162ns ±26%     134ns ±26%  -17.44%  (p=0.014 n=10+10)

name        old alloc/op   new alloc/op   delta
ReplaceAll     32.0B ± 0%     16.0B ± 0%  -50.00%  (p=0.000 n=10+10)

name        old allocs/op  new allocs/op  delta
ReplaceAll      2.00 ± 0%      1.00 ± 0%  -50.00%  (p=0.000 n=10+10)

Change-Id: Ia8377141d3adb84c7bd94e511ac8f739915aeb40
Reviewed-on: https://go-review.googlesource.com/c/go/+/245197
Run-TryBot: Martin Möhrmann <moehrmann@google.com>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Keith Randall <khr@golang.org>
src/strings/strings.go
src/strings/strings_test.go

index d6f5cea6e69409c03945fe9a761d8da04137ddb3..b429735feadf9d26d29c22d52440f9eb5a749d7f 100644 (file)
@@ -934,8 +934,8 @@ func Replace(s, old, new string, n int) string {
        }
 
        // Apply replacements to buffer.
-       t := make([]byte, len(s)+n*(len(new)-len(old)))
-       w := 0
+       var b Builder
+       b.Grow(len(s) + n*(len(new)-len(old)))
        start := 0
        for i := 0; i < n; i++ {
                j := start
@@ -947,12 +947,12 @@ func Replace(s, old, new string, n int) string {
                } else {
                        j += Index(s[start:], old)
                }
-               w += copy(t[w:], s[start:j])
-               w += copy(t[w:], new)
+               b.WriteString(s[start:j])
+               b.WriteString(new)
                start = j + len(old)
        }
-       w += copy(t[w:], s[start:])
-       return string(t[0:w])
+       b.WriteString(s[start:])
+       return b.String()
 }
 
 // ReplaceAll returns a copy of the string s with all
index c01c4dabc537bd16e921379d08b356c0e4b2f35b..09e5b27cc3857a6a98a0ef0b19cd05f1e9d536da 100644 (file)
@@ -1900,3 +1900,12 @@ func BenchmarkTrimSpace(b *testing.B) {
                })
        }
 }
+
+var stringSink string
+
+func BenchmarkReplaceAll(b *testing.B) {
+       b.ReportAllocs()
+       for i := 0; i < b.N; i++ {
+               stringSink = ReplaceAll("banana", "a", "<>")
+       }
+}