Skip to content

Instantly share code, notes, and snippets.

@seriousben
Last active March 12, 2020 19:55
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 seriousben/2f1063c79744b215dbb2f22c8386cb8a to your computer and use it in GitHub Desktop.
Save seriousben/2f1063c79744b215dbb2f22c8386cb8a to your computer and use it in GitHub Desktop.
golang benchmark template caching

golang benchmark template caching

Output

> go test -bench=. -test.benchtime=20s
goos: darwin
goarch: amd64
BenchmarkCached-12       	20000000	      1173 ns/op	     400 B/op	      10 allocs/op
BenchmarkNotCached-12    	 5000000	      7955 ns/op	    2766 B/op	      52 allocs/op
PASS
ok  	_/golang-benchmark-template-caching	72.913s
package main
import (
"bytes"
"testing"
"text/template"
)
var cachedTemplate = template.Must(template.New("master").Parse(`
<ol>
{{range .}}
<li>{{.}}</li>
{{end}}
</ol>
`))
func cached(data []string) {
var buffer bytes.Buffer
cachedTemplate.Execute(&buffer, data)
}
func notCached(data []string) {
var tmpl = template.Must(template.New("master").Parse(`
<ol>
{{range .}}
<li>{{.}}</li>
{{end}}
</ol>
`))
var buffer bytes.Buffer
tmpl.Execute(&buffer, data)
}
func BenchmarkCached(b *testing.B) {
b.ReportAllocs()
data := []string{"1", "2", "3"}
for i := 0; i < b.N; i++ {
cached(data)
}
}
func BenchmarkNotCached(b *testing.B) {
b.ReportAllocs()
data := []string{"1", "2", "3"}
for i := 0; i < b.N; i++ {
notCached(data)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment