From 7bcbb65d7879f17b185cee9ab4ab392da0bd865f Mon Sep 17 00:00:00 2001 From: Rui Ueyama Date: Wed, 11 Jun 2014 19:03:59 -0700 Subject: 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 --- src/pkg/strings/strings.go | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) (limited to 'src/pkg/strings/strings.go') diff --git a/src/pkg/strings/strings.go b/src/pkg/strings/strings.go index 5d46211d84..53bcd6b98a 100644 --- a/src/pkg/strings/strings.go +++ b/src/pkg/strings/strings.go @@ -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) } -- cgit v1.3-5-g9baa