github.com/karrick/go@v0.0.0-20170817181416-d5b0ec858b37/test/bench/go1/template_test.go (about) 1 // Copyright 2011 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // This benchmark tests text/template throughput, 6 // converting a large data structure with a simple template. 7 8 package go1 9 10 import ( 11 "bytes" 12 "io/ioutil" 13 "strings" 14 "testing" 15 "text/template" 16 ) 17 18 // After removing \t and \n this generates identical output to 19 // json.Marshal, making it easy to test for correctness. 20 const tmplText = ` 21 { 22 "tree":{{template "node" .Tree}}, 23 "username":"{{.Username}}" 24 } 25 {{define "node"}} 26 { 27 "name":"{{.Name}}", 28 "kids":[ 29 {{range $i, $k := .Kids}} 30 {{if $i}} 31 , 32 {{end}} 33 {{template "node" $k}} 34 {{end}} 35 ], 36 "cl_weight":{{.CLWeight}}, 37 "touches":{{.Touches}}, 38 "min_t":{{.MinT}}, 39 "max_t":{{.MaxT}}, 40 "mean_t":{{.MeanT}} 41 } 42 {{end}} 43 ` 44 45 func stripTabNL(r rune) rune { 46 if r == '\t' || r == '\n' { 47 return -1 48 } 49 return r 50 } 51 52 var tmpl = template.Must(template.New("main").Parse(strings.Map(stripTabNL, tmplText))) 53 54 func init() { 55 var buf bytes.Buffer 56 if err := tmpl.Execute(&buf, &jsondata); err != nil { 57 panic(err) 58 } 59 if !bytes.Equal(buf.Bytes(), jsonbytes) { 60 println(buf.Len(), len(jsonbytes)) 61 panic("wrong output") 62 } 63 } 64 65 func tmplexec() { 66 if err := tmpl.Execute(ioutil.Discard, &jsondata); err != nil { 67 panic(err) 68 } 69 } 70 71 func BenchmarkTemplate(b *testing.B) { 72 b.SetBytes(int64(len(jsonbytes))) 73 for i := 0; i < b.N; i++ { 74 tmplexec() 75 } 76 }