-
Notifications
You must be signed in to change notification settings - Fork 627
/
Copy pathbenchmark_test.go
99 lines (84 loc) · 2.1 KB
/
benchmark_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package main_test
import (
"bytes"
"io/ioutil"
"log"
"testing"
"encoding/json"
"github.com/mailru/easyjson"
"github.com/tidwall/gjson"
"github.com/elastic/go-elasticsearch/v7/_examples/encoding/model"
)
func BenchmarkSearchResults(b *testing.B) {
b.ReportAllocs()
input := fixture("testdata/response_search.json")
b.Run("json", func(b *testing.B) {
for i := 0; i < b.N; i++ {
var res model.SearchResponse
err := json.NewDecoder(bytes.NewReader(input.Bytes())).Decode(&res)
if err != nil {
b.Error(err)
}
}
})
b.Run("easyjson", func(b *testing.B) {
for i := 0; i < b.N; i++ {
var res model.SearchResponse
err := easyjson.UnmarshalFromReader(bytes.NewReader(input.Bytes()), &res)
if err != nil {
b.Error(err)
}
}
})
}
func BenchmarkClusterStats(b *testing.B) {
b.ReportAllocs()
input := fixture("testdata/response_cluster_stats.json")
b.Run("json - map", func(b *testing.B) {
for i := 0; i < b.N; i++ {
var out = make(map[string]interface{})
err := json.NewDecoder(bytes.NewReader(input.Bytes())).Decode(&out)
if err != nil {
b.Error(err)
}
}
})
b.Run("json - struct", func(b *testing.B) {
type ClusterHealthResponse struct {
ClusterName string `json:"cluster_name"`
Status string
Indices struct {
Count int
Docs struct {
Count int
}
}
}
for i := 0; i < b.N; i++ {
var out ClusterHealthResponse
err := json.NewDecoder(bytes.NewReader(input.Bytes())).Decode(&out)
if err != nil {
b.Error(err)
}
if len(out.ClusterName) < 3 {
b.Errorf("Unexpected len(%s)=%d", out.ClusterName, len(out.ClusterName))
}
}
})
b.Run("gjson", func(b *testing.B) {
for i := 0; i < b.N; i++ {
var out []gjson.Result
out = gjson.GetManyBytes(input.Bytes(), "cluster_name", "status", "indices.count", "indices.docs.count")
if len(out[0].String()) < 3 {
b.Errorf("Unexpected len(%s)=%d", out[0], len(out[0].String()))
}
}
})
}
func fixture(fname string) *bytes.Buffer {
payload, err := ioutil.ReadFile(fname)
if err != nil {
log.Fatalf("Error: %s", err)
}
return bytes.NewBuffer(payload)
}