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