Skip to content

Instantly share code, notes, and snippets.

@conradludgate
Created June 10, 2017 20:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save conradludgate/077ae4c150a980104d54c14c797cc8fb to your computer and use it in GitHub Desktop.
Save conradludgate/077ae4c150a980104d54c14c797cc8fb to your computer and use it in GitHub Desktop.
// Benchmark for https://github.com/wjh/beaver/issues/1
package main
import (
"bytes"
"fmt"
"os"
"strconv"
"testing"
"text/template"
)
var name = "Conrad"
var age = 18
// Output to match
// "Hello, My name is {name}. In 5 years I will be {age + 5} years old!"
var foo = ""
// built-in
func TestConcat(t *testing.T) {
fmt.Println("Hello, My name is " + name + ". In 5 years I will be " + strconv.Itoa(age+5) + " years old!")
}
func BenchmarkConcat(b *testing.B) {
for i := 0; i < b.N; i++ {
// Ugly, long and often rejected for the neater looking fmt.Printf
foo = "Hello, My name is " + name + ". In 5 years I will be " + strconv.Itoa(age+5) + " years old!"
foo = ""
}
}
// fmt
func TestSprintF(t *testing.T) {
fmt.Println(fmt.Sprintf("Hello, My name is %v. In 5 years I will be %v years old!", name, age+5))
}
func BenchmarkSprintf(b *testing.B) {
for i := 0; i < b.N; i++ {
// Most common because of neatness.
foo = fmt.Sprintf("Hello, My name is %v. In 5 years I will be %v years old!", name, age+5)
foo = ""
}
}
// text/template
// Not normally used but has similar formatting to the proposed formatting.
// Too powerful for what is required.
type data struct {
Name string
Age int
}
var fooBuffer = &bytes.Buffer{}
var temp, _ = (&template.Template{}).Parse("Hello, My name is {{.Name}}. In 5 years I will be {{.Age}} years old!")
func TestTextTemplate(t *testing.T) {
temp.Execute(os.Stdout, data{name, age + 5})
fmt.Println()
}
func BenchmarkTextTemplate(b *testing.B) {
for i := 0; i < b.N; i++ {
temp.Execute(fooBuffer, data{name, age + 5})
fooBuffer.Reset()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment