Skip to content

Commit 86ee892

Browse files
jsigngriesemer
authored andcommitted
strings: smarter growth of temporal buffer and avoid copying on return
The implementation for single strings had two optimization opportunities: 1. Grow the temporary buffer by known size before appending. 2. Avoid a full copy of the result since the underlying buffer won't be mutated afterward. Both things were leveraged by using a Builder instead of a byte slice. Relevant benchmark results: name old time/op new time/op delta SingleMatch-8 32.0µs ± 3% 26.1µs ± 3% -18.41% (p=0.000 n=9+10) name old speed new speed delta SingleMatch-8 469MB/s ± 3% 574MB/s ± 3% +22.56% (p=0.000 n=9+10) name old alloc/op new alloc/op delta SingleMatch-8 81.3kB ± 0% 49.0kB ± 0% -39.67% (p=0.000 n=10+10) name old allocs/op new allocs/op delta SingleMatch-8 19.0 ± 0% 11.0 ± 0% -42.11% (p=0.000 n=10+10) Change-Id: I23af56a15875206c0ff4ce29a51bec95fd48bb11 GitHub-Last-Rev: 403cfc3 GitHub-Pull-Request: #47766 Reviewed-on: https://go-review.googlesource.com/c/go/+/343089 Run-TryBot: Ian Lance Taylor <[email protected]> TryBot-Result: Go Bot <[email protected]> Reviewed-by: Ian Lance Taylor <[email protected]> Trust: Robert Griesemer <[email protected]>
1 parent 29d7e54 commit 86ee892

File tree

1 file changed

+6
-5
lines changed

1 file changed

+6
-5
lines changed

src/strings/replace.go

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -387,23 +387,24 @@ func makeSingleStringReplacer(pattern string, value string) *singleStringReplace
387387
}
388388

389389
func (r *singleStringReplacer) Replace(s string) string {
390-
var buf []byte
390+
var buf Builder
391391
i, matched := 0, false
392392
for {
393393
match := r.finder.next(s[i:])
394394
if match == -1 {
395395
break
396396
}
397397
matched = true
398-
buf = append(buf, s[i:i+match]...)
399-
buf = append(buf, r.value...)
398+
buf.Grow(match + len(r.value))
399+
buf.WriteString(s[i : i+match])
400+
buf.WriteString(r.value)
400401
i += match + len(r.finder.pattern)
401402
}
402403
if !matched {
403404
return s
404405
}
405-
buf = append(buf, s[i:]...)
406-
return string(buf)
406+
buf.WriteString(s[i:])
407+
return buf.String()
407408
}
408409

409410
func (r *singleStringReplacer) WriteString(w io.Writer, s string) (n int, err error) {

0 commit comments

Comments
 (0)