Source file
test/bench/go1/template_test.go
1
2
3
4
5
6
7
8 package go1
9
10 import (
11 "bytes"
12 "io"
13 "strings"
14 "testing"
15 "text/template"
16 )
17
18
19
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(io.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 }
77
View as plain text