diff options
| author | Rui Ueyama <ruiu@google.com> | 2014-06-11 19:03:59 -0700 |
|---|---|---|
| committer | Josh Bleecher Snyder <josharian@gmail.com> | 2014-06-11 19:03:59 -0700 |
| commit | 7bcbb65d7879f17b185cee9ab4ab392da0bd865f (patch) | |
| tree | 32e2589bcc426a1be9cf56e0f4fa5b1738a129b1 /src/pkg/bytes | |
| parent | 22a5d2cc961a0f115ebd61f41cabec6e668ed451 (diff) | |
| download | go-7bcbb65d7879f17b185cee9ab4ab392da0bd865f.tar.xz | |
bytes, strings: optimize Repeat
Call copy with as large buffer as possible to reduce the
number of function calls.
benchmark old ns/op new ns/op delta
BenchmarkBytesRepeat 540 162 -70.00%
BenchmarkStringsRepeat 563 177 -68.56%
LGTM=josharian
R=golang-codereviews, josharian, dave, dvyukov
CC=golang-codereviews
https://golang.org/cl/90550043
Diffstat (limited to 'src/pkg/bytes')
| -rw-r--r-- | src/pkg/bytes/bytes.go | 7 | ||||
| -rw-r--r-- | src/pkg/bytes/bytes_test.go | 6 |
2 files changed, 10 insertions, 3 deletions
diff --git a/src/pkg/bytes/bytes.go b/src/pkg/bytes/bytes.go index 0c53e4c0b7..d8b6f998b3 100644 --- a/src/pkg/bytes/bytes.go +++ b/src/pkg/bytes/bytes.go @@ -377,9 +377,10 @@ func Map(mapping func(r rune) rune, s []byte) []byte { // Repeat returns a new byte slice consisting of count copies of b. func Repeat(b []byte, count int) []byte { nb := make([]byte, len(b)*count) - bp := 0 - for i := 0; i < count; i++ { - bp += copy(nb[bp:], b) + bp := copy(nb, b) + for bp < len(nb) { + copy(nb[bp:], nb[:bp]) + bp *= 2 } return nb } diff --git a/src/pkg/bytes/bytes_test.go b/src/pkg/bytes/bytes_test.go index 394dd7a443..980c41d754 100644 --- a/src/pkg/bytes/bytes_test.go +++ b/src/pkg/bytes/bytes_test.go @@ -1232,3 +1232,9 @@ func BenchmarkTrimSpace(b *testing.B) { TrimSpace(s) } } + +func BenchmarkRepeat(b *testing.B) { + for i := 0; i < b.N; i++ { + Repeat([]byte("-"), 80) + } +} |
