Last active
October 14, 2015 07:02
-
-
Save jamband/e5c734b9e7b05fec6ca3 to your computer and use it in GitHub Desktop.
Go: Benchmark of repeat and concatenation of characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package s | |
import ( | |
"bytes" | |
"testing" | |
) | |
func A1() (s string) { | |
for i := 0; i < 1000; i++ { | |
s += "a" | |
} | |
return | |
} | |
func A2() string { | |
var b bytes.Buffer | |
for i := 0; i < 1000; i++ { | |
b.WriteString("a") | |
} | |
return b.String() | |
} | |
func A3() string { | |
b := make([]byte, 1000) | |
bp := copy(b, "a") | |
for bp < len(b) { | |
copy(b[bp:], b[:bp]) | |
bp *= 2 | |
} | |
return string(b) | |
} | |
func BenchmarkA1(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
A1() | |
} | |
} | |
func BenchmarkA2(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
A2() | |
} | |
} | |
func BenchmarkA3(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
A3() | |
} | |
} | |
// BenchmarkA1-4 10000 244578 ns/op | |
// BenchmarkA2-4 100000 18698 ns/op | |
// BenchmarkA3-4 3000000 464 ns/op | |
// A3() == strings.Repeat() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment