Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package main
import (
// "fmt"
"fmt"
"strings"
"testing"
)
// type Greeter interface {
// Hello(string) string
// }
// type AccumGreet interface {
// GreetReplicate(int32, string) string
// }
type SprintfGreeter struct{}
type ConcatGreeter struct{}
type BuilderGreeter struct{}
func (g SprintfGreeter) Hello(str string) string {
return fmt.Sprintf("Hello %s", str)
}
func (g ConcatGreeter) Hello(str string) string {
return "Hello " + str
}
func (g ConcatGreeter) GreetReplicate(n int, str string) string {
acc := ""
for i := 0; i < n; i++ {
acc += g.Hello(str)
}
return acc
}
func (g BuilderGreeter) Hello(str string) string {
var bb strings.Builder
_, _ = bb.WriteString("Hello ")
_, _ = bb.WriteString(str)
return bb.String()
}
func (g BuilderGreeter) GreetReplicate(n int, str string) string {
var bb strings.Builder
for i := 0; i < n; i++ {
_, _ = bb.WriteString("Hello ")
_, _ = bb.WriteString(str)
}
return bb.String()
}
func BenchmarkSprintfGreeter(b *testing.B) {
g := SprintfGreeter{}
for i := 0; i < b.N; i++ {
g.Hello("test")
}
}
func BenchmarkBuilderGreeter(b *testing.B) {
g := BuilderGreeter{}
for i := 0; i < b.N; i++ {
g.Hello("test")
}
}
func BenchmarkConcatGreeter(b *testing.B) {
g := ConcatGreeter{}
for i := 0; i < b.N; i++ {
g.Hello("test")
}
}
////////////////////
func BenchmarkBuilderReplicate2(b *testing.B) {
g := BuilderGreeter{}
for i := 0; i < b.N; i++ {
g.GreetReplicate(2, "test")
}
}
func BenchmarkConcatReplicate2(b *testing.B) {
g := ConcatGreeter{}
for i := 0; i < b.N; i++ {
g.GreetReplicate(2, "test")
}
}
func BenchmarkBuilderReplicate4(b *testing.B) {
g := BuilderGreeter{}
for i := 0; i < b.N; i++ {
g.GreetReplicate(4, "test")
}
}
func BenchmarkConcatReplicate4(b *testing.B) {
g := ConcatGreeter{}
for i := 0; i < b.N; i++ {
g.GreetReplicate(4, "test")
}
}
func BenchmarkBuilderReplicate8(b *testing.B) {
g := BuilderGreeter{}
for i := 0; i < b.N; i++ {
g.GreetReplicate(8, "test")
}
}
func BenchmarkConcatReplicate8(b *testing.B) {
g := ConcatGreeter{}
for i := 0; i < b.N; i++ {
g.GreetReplicate(8, "test")
}
}
func BenchmarkBuilderReplicate16(b *testing.B) {
g := BuilderGreeter{}
for i := 0; i < b.N; i++ {
g.GreetReplicate(16, "test")
}
}
func BenchmarkConcatReplicate16(b *testing.B) {
g := ConcatGreeter{}
for i := 0; i < b.N; i++ {
g.GreetReplicate(16, "test")
}
}
func BenchmarkBuilderReplicate32(b *testing.B) {
g := BuilderGreeter{}
for i := 0; i < b.N; i++ {
g.GreetReplicate(32, "test")
}
}
func BenchmarkConcatReplicate32(b *testing.B) {
g := ConcatGreeter{}
for i := 0; i < b.N; i++ {
g.GreetReplicate(32, "test")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment