]> Cypherpunks repositories - gostls13.git/commitdiff
bytes, strings: optimize Repeat
authorRui Ueyama <ruiu@google.com>
Thu, 12 Jun 2014 02:03:59 +0000 (19:03 -0700)
committerJosh Bleecher Snyder <josharian@gmail.com>
Thu, 12 Jun 2014 02:03:59 +0000 (19:03 -0700)
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

src/pkg/bytes/bytes.go
src/pkg/bytes/bytes_test.go
src/pkg/strings/strings.go
src/pkg/strings/strings_test.go

index 0c53e4c0b71262b7dc015cb185ce1d486d8dd841..d8b6f998b3cba58dc2273750bce19c04cba53bcd 100644 (file)
@@ -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
 }
index 394dd7a443d93b29dbd6b491abd94863a28f1666..980c41d754ddfbcbb135daa0adf98bb940848bc1 100644 (file)
@@ -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)
+       }
+}
index 5d46211d84e5e395ae0c7a0479c68f8ffcbda6db..53bcd6b98a67c82ddf58b4aadb0902069a3eed42 100644 (file)
@@ -423,9 +423,10 @@ func Map(mapping func(rune) rune, s string) string {
 // Repeat returns a new string consisting of count copies of the string s.
 func Repeat(s string, count int) string {
        b := make([]byte, len(s)*count)
-       bp := 0
-       for i := 0; i < count; i++ {
-               bp += copy(b[bp:], s)
+       bp := copy(b, s)
+       for bp < len(b) {
+               copy(b[bp:], b[:bp])
+               bp *= 2
        }
        return string(b)
 }
index e40a18015e21e355322153e441bbdc911fcc5d31..95102b56fa5d5ca6119d565dd20d1a6099726507 100644 (file)
@@ -1174,3 +1174,9 @@ func BenchmarkSplit3(b *testing.B) {
                Split(benchInputHard, "hello")
        }
 }
+
+func BenchmarkRepeat(b *testing.B) {
+       for i := 0; i < b.N; i++ {
+               Repeat("-", 80)
+       }
+}