Debian Codegraph @

json/golang_bench_test.go

raw
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 // Large data benchmark.
6 // The JSON data is a summary of agl's changes in the
7 // go, webkit, and chromium open source projects.
8 // We benchmark converting between the JSON form
9 // and in-memory data structures.
10
11 package json
12
13 import (
14 "bytes"
15 "compress/gzip"
16 "fmt"
17 "io"
18 "os"
19 "reflect"
20 "runtime"
21 "strings"
22 "sync"
23 "testing"
24 )
25
26 type codeResponse struct {
27 Tree *codeNode `json:"tree"`
28 Username string `json:"username"`
29 }
30
31 type codeNode struct {
32 Name string `json:"name"`
33 Kids []*codeNode `json:"kids"`
34 CLWeight float64 `json:"cl_weight"`
35 Touches int `json:"touches"`
36 MinT int64 `json:"min_t"`
37 MaxT int64 `json:"max_t"`
38 MeanT int64 `json:"mean_t"`
39 }
40
41 var (
42 codeJSON []byte
43 codeStruct codeResponse
44 )
45
46 func codeInit() {
47 f, err := os.Open("testdata/code.json.gz")
48 if err != nil {
49 panic(err)
50 }
51 defer f.Close()
52 gz, err := gzip.NewReader(f)
53 if err != nil {
54 panic(err)
55 }
56 data, err := io.ReadAll(gz)
57 if err != nil {
58 panic(err)
59 }
60
61 codeJSON = data
62
63 if err := Unmarshal(codeJSON, &codeStruct); err != nil {
64 panic("unmarshal code.json: " + err.Error())
65 }
66
67 if data, err = Marshal(&codeStruct); err != nil {
68 panic("marshal code.json: " + err.Error())
69 }
70
71 if !bytes.Equal(data, codeJSON) {
72 println("different lengths", len(data), len(codeJSON))
73 for i := range min(len(data), len(codeJSON)) {
74 if data[i] != codeJSON[i] {
75 println("re-marshal: changed at byte", i)
76 println("orig: ", string(codeJSON[i-10:i+10]))
77 println("new: ", string(data[i-10:i+10]))
78 break
79 }
80 }
81 panic("re-marshal code.json: different result")
82 }
83 }
84
85 func BenchmarkCodeEncoder(b *testing.B) {
86 b.ReportAllocs()
87 if codeJSON == nil {
88 b.StopTimer()
89 codeInit()
90 b.StartTimer()
91 }
92 b.RunParallel(func(pb *testing.PB) {
93 enc := NewEncoder(io.Discard)
94 for pb.Next() {
95 if err := enc.Encode(&codeStruct); err != nil {
96 b.Fatal("Encode:", err)
97 }
98 }
99 })
100 b.SetBytes(int64(len(codeJSON)))
101 }
102
103 func BenchmarkCodeMarshal(b *testing.B) {
104 b.ReportAllocs()
105 if codeJSON == nil {
106 b.StopTimer()
107 codeInit()
108 b.StartTimer()
109 }
110 b.RunParallel(func(pb *testing.PB) {
111 for pb.Next() {
112 if _, err := Marshal(&codeStruct); err != nil {
113 b.Fatal("Marshal:", err)
114 }
115 }
116 })
117 b.SetBytes(int64(len(codeJSON)))
118 }
119
120 func benchMarshalBytes(n int) func(*testing.B) {
121 sample := []byte("hello world")
122 // Use a struct pointer, to avoid an allocation when passing it as an
123 // interface parameter to Marshal.
124 v := &struct {
125 Bytes []byte
126 }{
127 bytes.Repeat(sample, (n/len(sample))+1)[:n],
128 }
129 return func(b *testing.B) {
130 for range b.N {
131 if _, err := Marshal(v); err != nil {
132 b.Fatal("Marshal:", err)
133 }
134 }
135 }
136 }
137
138 func BenchmarkMarshalBytes(b *testing.B) {
139 b.ReportAllocs()
140 // 32 fits within encodeState.scratch.
141 b.Run("32", benchMarshalBytes(32))
142 // 256 doesn't fit in encodeState.scratch, but is small enough to
143 // allocate and avoid the slower base64.NewEncoder.
144 b.Run("256", benchMarshalBytes(256))
145 // 4096 is large enough that we want to avoid allocating for it.
146 b.Run("4096", benchMarshalBytes(4096))
147 }
148
149 func BenchmarkCodeDecoder(b *testing.B) {
150 b.ReportAllocs()
151 if codeJSON == nil {
152 b.StopTimer()
153 codeInit()
154 b.StartTimer()
155 }
156 b.RunParallel(func(pb *testing.PB) {
157 var buf bytes.Buffer
158 dec := NewDecoder(&buf)
159 var r codeResponse
160 for pb.Next() {
161 buf.Write(codeJSON)
162 // hide EOF
163 buf.WriteByte('\n')
164 buf.WriteByte('\n')
165 buf.WriteByte('\n')
166 if err := dec.Decode(&r); err != nil {
167 b.Fatal("Decode:", err)
168 }
169 }
170 })
171 b.SetBytes(int64(len(codeJSON)))
172 }
173
174 func BenchmarkUnicodeDecoder(b *testing.B) {
175 b.ReportAllocs()
176 j := []byte(`"\uD83D\uDE01"`)
177 b.SetBytes(int64(len(j)))
178 r := bytes.NewReader(j)
179 dec := NewDecoder(r)
180 var out string
181 b.ResetTimer()
182 for range b.N {
183 if err := dec.Decode(&out); err != nil {
184 b.Fatal("Decode:", err)
185 }
186 r.Seek(0, 0)
187 }
188 }
189
190 func BenchmarkDecoderStream(b *testing.B) {
191 b.ReportAllocs()
192 b.StopTimer()
193 var buf bytes.Buffer
194 dec := NewDecoder(&buf)
195 buf.WriteString(`"` + strings.Repeat("x", 1000000) + `"` + "\n\n\n")
196 var x any
197 if err := dec.Decode(&x); err != nil {
198 b.Fatal("Decode:", err)
199 }
200 ones := strings.Repeat(" 1\n", 300000) + "\n\n\n"
201 b.StartTimer()
202 for i := range b.N {
203 // XXX: making use of the index variable
204 // is probably a misuse of b.N loops.
205 if i%300000 == 0 {
206 buf.WriteString(ones)
207 }
208 x = nil
209 if err := dec.Decode(&x); err != nil || x != 1.0 {
210 b.Fatalf("Decode: %v after %d", err, i)
211 }
212 }
213 }
214
215 func BenchmarkCodeUnmarshal(b *testing.B) {
216 b.ReportAllocs()
217 if codeJSON == nil {
218 b.StopTimer()
219 codeInit()
220 b.StartTimer()
221 }
222 b.RunParallel(func(pb *testing.PB) {
223 for pb.Next() {
224 var r codeResponse
225 if err := Unmarshal(codeJSON, &r); err != nil {
226 b.Fatal("Unmarshal:", err)
227 }
228 }
229 })
230 b.SetBytes(int64(len(codeJSON)))
231 }
232
233 func BenchmarkCodeUnmarshalReuse(b *testing.B) {
234 b.ReportAllocs()
235 if codeJSON == nil {
236 b.StopTimer()
237 codeInit()
238 b.StartTimer()
239 }
240 b.RunParallel(func(pb *testing.PB) {
241 var r codeResponse
242 for pb.Next() {
243 if err := Unmarshal(codeJSON, &r); err != nil {
244 b.Fatal("Unmarshal:", err)
245 }
246 }
247 })
248 b.SetBytes(int64(len(codeJSON)))
249 }
250
251 func BenchmarkUnmarshalString(b *testing.B) {
252 b.ReportAllocs()
253 data := []byte(`"hello, world"`)
254 b.RunParallel(func(pb *testing.PB) {
255 var s string
256 for pb.Next() {
257 if err := Unmarshal(data, &s); err != nil {
258 b.Fatal("Unmarshal:", err)
259 }
260 }
261 })
262 }
263
264 func BenchmarkUnmarshalObjectMixed(b *testing.B) {
265 b.ReportAllocs()
266 data := []byte(`{"string":"hello world","time":"2025-07-17T18:40:04.338Z","bool":true,"integer":42,"decimal":3.14,"null":null,"object":{"hello":"world"},"array":[1,2,3]}`)
267 b.RunParallel(func(pb *testing.PB) {
268 var m map[string]any
269 for pb.Next() {
270 if err := Unmarshal(data, &m); err != nil {
271 b.Fatal("Unmarshal:", err)
272 }
273 }
274 })
275 }
276
277 func BenchmarkUnmarshalArrayMixed(b *testing.B) {
278 b.ReportAllocs()
279 data := []byte(`["hello world","2025-07-17T18:40:04.338Z",true,42,3.14,null,{"hello":"world"},[1,2,3]]`)
280 b.RunParallel(func(pb *testing.PB) {
281 var a []any
282 for pb.Next() {
283 if err := Unmarshal(data, &a); err != nil {
284 b.Fatal("Unmarshal:", err)
285 }
286 }
287 })
288 }
289
290 func BenchmarkUnmarshalFloat64(b *testing.B) {
291 b.ReportAllocs()
292 data := []byte(`3.14`)
293 b.RunParallel(func(pb *testing.PB) {
294 var f float64
295 for pb.Next() {
296 if err := Unmarshal(data, &f); err != nil {
297 b.Fatal("Unmarshal:", err)
298 }
299 }
300 })
301 }
302
303 func BenchmarkUnmarshalInt64(b *testing.B) {
304 b.ReportAllocs()
305 data := []byte(`3`)
306 b.RunParallel(func(pb *testing.PB) {
307 var x int64
308 for pb.Next() {
309 if err := Unmarshal(data, &x); err != nil {
310 b.Fatal("Unmarshal:", err)
311 }
312 }
313 })
314 }
315
316 func BenchmarkIssue10335(b *testing.B) {
317 b.ReportAllocs()
318 j := []byte(`{"a":{ }}`)
319 b.RunParallel(func(pb *testing.PB) {
320 var s struct{}
321 for pb.Next() {
322 if err := Unmarshal(j, &s); err != nil {
323 b.Fatal(err)
324 }
325 }
326 })
327 }
328
329 func BenchmarkUnmapped(b *testing.B) {
330 b.ReportAllocs()
331 j := []byte(`{"s": "hello", "y": 2, "o": {"x": 0}, "a": [1, 99, {"x": 1}]}`)
332 b.RunParallel(func(pb *testing.PB) {
333 var s struct{}
334 for pb.Next() {
335 if err := Unmarshal(j, &s); err != nil {
336 b.Fatal(err)
337 }
338 }
339 })
340 }
341
342 func BenchmarkTypeFieldsCache(b *testing.B) {
343 b.ReportAllocs()
344 var maxTypes int = 1e6
345 if testenv.Builder() != "" {
346 maxTypes = 1e3 // restrict cache sizes on builders
347 }
348
349 // Dynamically generate many new types.
350 types := make([]reflect.Type, maxTypes)
351 fs := []reflect.StructField{{
352 Type: reflect.TypeOf(""),
353 Index: []int{0},
354 }}
355 for i := range types {
356 fs[0].Name = fmt.Sprintf("TypeFieldsCache%d", i)
357 types[i] = reflect.StructOf(fs)
358 }
359
360 // clearClear clears the cache. Other JSON operations, must not be running.
361 clearCache := func() {
362 fieldCache = sync.Map{}
363 }
364
365 // MissTypes tests the performance of repeated cache misses.
366 // This measures the time to rebuild a cache of size nt.
367 for nt := 1; nt <= maxTypes; nt *= 10 {
368 ts := types[:nt]
369 b.Run(fmt.Sprintf("MissTypes%d", nt), func(b *testing.B) {
370 nc := runtime.GOMAXPROCS(0)
371 for range b.N {
372 clearCache()
373 var wg sync.WaitGroup
374 for j := range nc {
375 wg.Add(1)
376 go func(j int) {
377 for _, t := range ts[(j*len(ts))/nc : ((j+1)*len(ts))/nc] {
378 cachedTypeFields(t)
379 }
380 wg.Done()
381 }(j)
382 }
383 wg.Wait()
384 }
385 })
386 }
387
388 // HitTypes tests the performance of repeated cache hits.
389 // This measures the average time of each cache lookup.
390 for nt := 1; nt <= maxTypes; nt *= 10 {
391 // Pre-warm a cache of size nt.
392 clearCache()
393 for _, t := range types[:nt] {
394 cachedTypeFields(t)
395 }
396 b.Run(fmt.Sprintf("HitTypes%d", nt), func(b *testing.B) {
397 b.RunParallel(func(pb *testing.PB) {
398 for pb.Next() {
399 cachedTypeFields(types[0])
400 }
401 })
402 })
403 }
404 }