diff options
| author | Cherry Zhang <cherryyz@google.com> | 2020-08-21 14:18:06 -0400 |
|---|---|---|
| committer | Cherry Zhang <cherryyz@google.com> | 2020-08-21 14:18:06 -0400 |
| commit | 0ef562592fe05b50b0ae8fce495ee7e2eec791f0 (patch) | |
| tree | d1c0f668e473ebdcb4a30e190008043bdb223bd9 /src/strings | |
| parent | ac5c406ef0ab20e2a11f57470271266ef4265221 (diff) | |
| parent | 9679b307334bce77cc6e50751956a4c717e9458c (diff) | |
| download | go-0ef562592fe05b50b0ae8fce495ee7e2eec791f0.tar.xz | |
[dev.link] all: merge branch 'master' into dev.link
Change-Id: Ic66b5138f3ecd9e9a48d7ab05782297c06e4a5b5
Diffstat (limited to 'src/strings')
| -rw-r--r-- | src/strings/strings.go | 12 | ||||
| -rw-r--r-- | src/strings/strings_test.go | 9 |
2 files changed, 15 insertions, 6 deletions
diff --git a/src/strings/strings.go b/src/strings/strings.go index d6f5cea6e6..b429735fea 100644 --- a/src/strings/strings.go +++ b/src/strings/strings.go @@ -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 diff --git a/src/strings/strings_test.go b/src/strings/strings_test.go index c01c4dabc5..09e5b27cc3 100644 --- a/src/strings/strings_test.go +++ b/src/strings/strings_test.go @@ -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", "<>") + } +} |
