Debian Codegraph @

benchmarks/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 benchmark
12
13 import (
14 "bytes"
15 "compress/gzip"
16 "fmt"
17 "io"
18 "os"
19 "strings"
20 "testing"
21
22 stdjson "encoding/json"
23
24 "github.com/goccy/go-json"
25 jsoniter "github.com/json-iterator/go"
26 segmentiojson "github.com/segmentio/encoding/json"
27 "github.com/wI2L/jettison"
28 )
29
30 type codeResponse struct {
31 Tree *codeNode `json:"tree"`
32 Username string `json:"username"`
33 }
34
35 type codeNode struct {
36 Name string `json:"name"`
37 Kids []*codeNode `json:"kids"`
38 CLWeight float64 `json:"cl_weight"`
39 Touches int `json:"touches"`
40 MinT int64 `json:"min_t"`
41 MaxT int64 `json:"max_t"`
42 MeanT int64 `json:"mean_t"`
43 }
44
45 var codeJSON []byte
46 var codeStruct codeResponse
47
48 func codeInit() {
49 f, err := os.Open("testdata/code.json.gz")
50 if err != nil {
51 panic(err)
52 }
53 defer f.Close()
54 gz, err := gzip.NewReader(f)
55 if err != nil {
56 panic(err)
57 }
58 data, err := io.ReadAll(gz)
59 if err != nil {
60 panic(err)
61 }
62
63 codeJSON = data
64
65 if err := stdjson.Unmarshal(codeJSON, &codeStruct); err != nil {
66 panic("unmarshal code.json: " + err.Error())
67 }
68 {
69 stdjsonbytes, err := stdjson.Marshal(&codeStruct)
70 if err != nil {
71 panic("marshal code.json: " + err.Error())
72 }
73 jsonbytes, err := json.Marshal(&codeStruct)
74 if err != nil {
75 panic("marshal code.json: " + err.Error())
76 }
77 if len(stdjsonbytes) != len(jsonbytes) {
78 panic(fmt.Sprintf("stdjson = %d but go-json = %d", len(stdjsonbytes), len(jsonbytes)))
79 }
80 }
81 if _, err := json.Marshal(&codeStruct); err != nil {
82 panic("marshal code.json: " + err.Error())
83 }
84 if !bytes.Equal(data, codeJSON) {
85 println("different lengths", len(data), len(codeJSON))
86 for i := 0; i < len(data) && i < len(codeJSON); i++ {
87 if data[i] != codeJSON[i] {
88 println("re-marshal: changed at byte", i)
89 println("orig: ", string(codeJSON[i-10:i+10]))
90 println("new: ", string(data[i-10:i+10]))
91 break
92 }
93 }
94 panic("re-marshal code.json: different result")
95 }
96 }
97
98 func Benchmark_EncodeBigData_GoJson(b *testing.B) {
99 b.ReportAllocs()
100 if codeJSON == nil {
101 b.StopTimer()
102 codeInit()
103 b.StartTimer()
104 }
105 b.RunParallel(func(pb *testing.PB) {
106 enc := json.NewEncoder(io.Discard)
107 for pb.Next() {
108 if err := enc.Encode(&codeStruct); err != nil {
109 b.Fatal("Encode:", err)
110 }
111 }
112 })
113 b.SetBytes(int64(len(codeJSON)))
114 }
115
116 func Benchmark_EncodeBigData_EncodingJson(b *testing.B) {
117 b.ReportAllocs()
118 if codeJSON == nil {
119 b.StopTimer()
120 codeInit()
121 b.StartTimer()
122 }
123 b.RunParallel(func(pb *testing.PB) {
124 enc := stdjson.NewEncoder(io.Discard)
125 for pb.Next() {
126 if err := enc.Encode(&codeStruct); err != nil {
127 b.Fatal("Encode:", err)
128 }
129 }
130 })
131 b.SetBytes(int64(len(codeJSON)))
132 }
133
134 func Benchmark_EncodeBigData_JsonIter(b *testing.B) {
135 b.ReportAllocs()
136 if codeJSON == nil {
137 b.StopTimer()
138 codeInit()
139 b.StartTimer()
140 }
141 var json = jsoniter.ConfigCompatibleWithStandardLibrary
142 b.RunParallel(func(pb *testing.PB) {
143 enc := json.NewEncoder(io.Discard)
144 for pb.Next() {
145 if err := enc.Encode(&codeStruct); err != nil {
146 b.Fatal("Encode:", err)
147 }
148 }
149 })
150 b.SetBytes(int64(len(codeJSON)))
151 }
152
153 func Benchmark_EncodeBigData_SegmentioJson(b *testing.B) {
154 b.ReportAllocs()
155 if codeJSON == nil {
156 b.StopTimer()
157 codeInit()
158 b.StartTimer()
159 }
160 b.RunParallel(func(pb *testing.PB) {
161 enc := segmentiojson.NewEncoder(io.Discard)
162 for pb.Next() {
163 if err := enc.Encode(&codeStruct); err != nil {
164 b.Fatal("Encode:", err)
165 }
166 }
167 })
168 b.SetBytes(int64(len(codeJSON)))
169 }
170
171 func Benchmark_MarshalBigData_GoJson(b *testing.B) {
172 b.ReportAllocs()
173 if codeJSON == nil {
174 b.StopTimer()
175 codeInit()
176 b.StartTimer()
177 }
178
179 b.RunParallel(func(pb *testing.PB) {
180 for pb.Next() {
181 if _, err := json.Marshal(&codeStruct); err != nil {
182 b.Fatal("Marshal:", err)
183 }
184 }
185 })
186 b.SetBytes(int64(len(codeJSON)))
187 }
188
189 func Benchmark_MarshalBigData_EncodingJson(b *testing.B) {
190 b.ReportAllocs()
191 if codeJSON == nil {
192 b.StopTimer()
193 codeInit()
194 b.StartTimer()
195 }
196 b.RunParallel(func(pb *testing.PB) {
197 for pb.Next() {
198 if _, err := stdjson.Marshal(&codeStruct); err != nil {
199 b.Fatal("Marshal:", err)
200 }
201 }
202 })
203 b.SetBytes(int64(len(codeJSON)))
204 }
205
206 func Benchmark_MarshalBigData_JsonIter(b *testing.B) {
207 b.ReportAllocs()
208 if codeJSON == nil {
209 b.StopTimer()
210 codeInit()
211 b.StartTimer()
212 }
213 var json = jsoniter.ConfigCompatibleWithStandardLibrary
214 b.RunParallel(func(pb *testing.PB) {
215 for pb.Next() {
216 if _, err := json.Marshal(&codeStruct); err != nil {
217 b.Fatal("Marshal:", err)
218 }
219 }
220 })
221 b.SetBytes(int64(len(codeJSON)))
222 }
223
224 func Benchmark_MarshalBigData_Jettison(b *testing.B) {
225 b.ReportAllocs()
226 if codeJSON == nil {
227 b.StopTimer()
228 codeInit()
229 b.StartTimer()
230 }
231 b.RunParallel(func(pb *testing.PB) {
232 for pb.Next() {
233 if _, err := jettison.Marshal(&codeStruct); err != nil {
234 b.Fatal("Marshal:", err)
235 }
236 }
237 })
238 b.SetBytes(int64(len(codeJSON)))
239 }
240
241 func Benchmark_MarshalBigData_SegmentioJson(b *testing.B) {
242 b.ReportAllocs()
243 if codeJSON == nil {
244 b.StopTimer()
245 codeInit()
246 b.StartTimer()
247 }
248 b.RunParallel(func(pb *testing.PB) {
249 for pb.Next() {
250 if _, err := segmentiojson.Marshal(&codeStruct); err != nil {
251 b.Fatal("Marshal:", err)
252 }
253 }
254 })
255 b.SetBytes(int64(len(codeJSON)))
256 }
257
258 func benchMarshalBytes(n int, marshaler func(any) ([]byte, error)) func(*testing.B) {
259 sample := []byte("hello world")
260 // Use a struct pointer, to avoid an allocation when passing it as an
261 // interface parameter to Marshal.
262 v := &struct {
263 Bytes []byte
264 }{
265 bytes.Repeat(sample, (n/len(sample))+1)[:n],
266 }
267 return func(b *testing.B) {
268 b.ReportAllocs()
269 for i := 0; i < b.N; i++ {
270 if _, err := marshaler(v); err != nil {
271 b.Fatal("Marshal:", err)
272 }
273 }
274 }
275 }
276
277 func Benchmark_MarshalBytes_EncodingJson(b *testing.B) {
278 // 32 fits within encodeState.scratch.
279 b.Run("32", benchMarshalBytes(32, stdjson.Marshal))
280 // 256 doesn't fit in encodeState.scratch, but is small enough to
281 // allocate and avoid the slower base64.NewEncoder.
282 b.Run("256", benchMarshalBytes(256, stdjson.Marshal))
283 // 4096 is large enough that we want to avoid allocating for it.
284 b.Run("4096", benchMarshalBytes(4096, stdjson.Marshal))
285 }
286
287 func Benchmark_MarshalBytes_JsonIter(b *testing.B) {
288 var json = jsoniter.ConfigCompatibleWithStandardLibrary
289 // 32 fits within encodeState.scratch.
290 b.Run("32", benchMarshalBytes(32, json.Marshal))
291 // 256 doesn't fit in encodeState.scratch, but is small enough to
292 // allocate and avoid the slower base64.NewEncoder.
293 b.Run("256", benchMarshalBytes(256, json.Marshal))
294 // 4096 is large enough that we want to avoid allocating for it.
295 b.Run("4096", benchMarshalBytes(4096, json.Marshal))
296 }
297
298 func Benchmark_MarshalBytes_GoJson(b *testing.B) {
299 b.ReportAllocs()
300 // 32 fits within encodeState.scratch.
301 b.Run("32", benchMarshalBytes(32, json.Marshal))
302 // 256 doesn't fit in encodeState.scratch, but is small enough to
303 // allocate and avoid the slower base64.NewEncoder.
304 b.Run("256", benchMarshalBytes(256, json.Marshal))
305 // 4096 is large enough that we want to avoid allocating for it.
306 b.Run("4096", benchMarshalBytes(4096, json.Marshal))
307 }
308
309 func Benchmark_EncodeRawMessage_EncodingJson(b *testing.B) {
310 b.ReportAllocs()
311
312 m := struct {
313 A int
314 B json.RawMessage
315 }{}
316
317 b.RunParallel(func(pb *testing.PB) {
318 enc := stdjson.NewEncoder(io.Discard)
319 for pb.Next() {
320 if err := enc.Encode(&m); err != nil {
321 b.Fatal("Encode:", err)
322 }
323 }
324 })
325 }
326
327 func Benchmark_EncodeRawMessage_JsonIter(b *testing.B) {
328 b.ReportAllocs()
329
330 m := struct {
331 A int
332 B json.RawMessage
333 }{}
334
335 var json = jsoniter.ConfigCompatibleWithStandardLibrary
336
337 b.RunParallel(func(pb *testing.PB) {
338 enc := json.NewEncoder(io.Discard)
339 for pb.Next() {
340 if err := enc.Encode(&m); err != nil {
341 b.Fatal("Encode:", err)
342 }
343 }
344 })
345 }
346
347 // a raw message which holds a document: what a marshaler returns is validated and compacted.
348 var rawMessageDocument = json.RawMessage("[" + strings.Repeat(`{"id":123456,"name":"alice","tags":["a","b","c"],"score":12.5,"active":true,"nested":{"x":1,"y":null}},`, 20) + `{"end":true}]`)
349
350 func Benchmark_EncodeRawMessageDocument_GoJson(b *testing.B) {
351 b.ReportAllocs()
352 b.SetBytes(int64(len(rawMessageDocument)))
353 m := struct {
354 A int
355 B json.RawMessage
356 }{B: rawMessageDocument}
357 for i := 0; i < b.N; i++ {
358 if _, err := json.Marshal(&m); err != nil {
359 b.Fatal("Marshal:", err)
360 }
361 }
362 }
363
364 func Benchmark_EncodeRawMessageDocument_EncodingJson(b *testing.B) {
365 b.ReportAllocs()
366 b.SetBytes(int64(len(rawMessageDocument)))
367 m := struct {
368 A int
369 B stdjson.RawMessage
370 }{B: stdjson.RawMessage(rawMessageDocument)}
371 for i := 0; i < b.N; i++ {
372 if _, err := stdjson.Marshal(&m); err != nil {
373 b.Fatal("Marshal:", err)
374 }
375 }
376 }
377
378 func Benchmark_EncodeRawMessage_GoJson(b *testing.B) {
379 b.ReportAllocs()
380
381 m := struct {
382 A int
383 B json.RawMessage
384 }{}
385 b.RunParallel(func(pb *testing.PB) {
386 enc := json.NewEncoder(io.Discard)
387 for pb.Next() {
388 if err := enc.Encode(&m); err != nil {
389 b.Fatal("Encode:", err)
390 }
391 }
392 })
393 }
394
395 func Benchmark_MarshalString_EncodingJson(b *testing.B) {
396 b.ReportAllocs()
397 j := struct {
398 Bar string `json:"bar,string"`
399 }{
400 Bar: `foobar`,
401 }
402 b.RunParallel(func(pb *testing.PB) {
403 for pb.Next() {
404 if _, err := stdjson.Marshal(&j); err != nil {
405 b.Fatal(err)
406 }
407 }
408 })
409 }
410
411 func Benchmark_MarshalString_JsonIter(b *testing.B) {
412 b.ReportAllocs()
413 j := struct {
414 Bar string `json:"bar,string"`
415 }{
416 Bar: `foobar`,
417 }
418 var json = jsoniter.ConfigCompatibleWithStandardLibrary
419 b.RunParallel(func(pb *testing.PB) {
420 for pb.Next() {
421 if _, err := json.Marshal(&j); err != nil {
422 b.Fatal(err)
423 }
424 }
425 })
426 }
427
428 func Benchmark_MarshalString_GoJson(b *testing.B) {
429 b.ReportAllocs()
430 j := struct {
431 Bar string `json:"bar,string"`
432 }{
433 Bar: `foobar`,
434 }
435 b.RunParallel(func(pb *testing.PB) {
436 for pb.Next() {
437 if _, err := json.Marshal(&j); err != nil {
438 b.Fatal(err)
439 }
440 }
441 })
442 }
443
444 func BenchmarkCodeDecoder(b *testing.B) {
445 b.ReportAllocs()
446 if codeJSON == nil {
447 b.StopTimer()
448 codeInit()
449 b.StartTimer()
450 }
451 b.RunParallel(func(pb *testing.PB) {
452 var buf bytes.Buffer
453 dec := json.NewDecoder(&buf)
454 var r codeResponse
455 for pb.Next() {
456 buf.Write(codeJSON)
457 // hide EOF
458 buf.WriteByte('\n')
459 buf.WriteByte('\n')
460 buf.WriteByte('\n')
461 if err := dec.Decode(&r); err != nil {
462 if err != io.EOF {
463 b.Fatal("Decode:", err)
464 }
465 }
466 }
467 })
468 b.SetBytes(int64(len(codeJSON)))
469 }
470
471 func BenchmarkUnicodeDecoder(b *testing.B) {
472 b.ReportAllocs()
473 j := []byte(`"\uD83D\uDE01"`)
474 b.SetBytes(int64(len(j)))
475 r := bytes.NewReader(j)
476 dec := json.NewDecoder(r)
477 var out string
478 b.ResetTimer()
479 for i := 0; i < b.N; i++ {
480 if err := dec.Decode(&out); err != nil {
481 if err != io.EOF {
482 b.Fatal("Decode:", err)
483 }
484 }
485 r.Seek(0, 0)
486 }
487 }
488
489 func BenchmarkDecoderStream(b *testing.B) {
490 b.ReportAllocs()
491 b.StopTimer()
492 var buf bytes.Buffer
493 dec := json.NewDecoder(&buf)
494 buf.WriteString(`"` + strings.Repeat("x", 1000000) + `"` + "\n\n\n")
495 var x any
496 if err := dec.Decode(&x); err != nil {
497 b.Fatal("Decode:", err)
498 }
499 ones := strings.Repeat(" 1\n", 300000) + "\n\n\n"
500 b.StartTimer()
501 for i := 0; i < b.N; i++ {
502 if i%300000 == 0 {
503 buf.WriteString(ones)
504 }
505 x = nil
506 if err := dec.Decode(&x); err != nil || x != 1.0 {
507 if err != io.EOF {
508 b.Fatalf("Decode: %v after %d", err, i)
509 }
510 }
511 }
512 }
513
514 func BenchmarkCodeUnmarshal(b *testing.B) {
515 b.ReportAllocs()
516 if codeJSON == nil {
517 b.StopTimer()
518 codeInit()
519 b.StartTimer()
520 }
521 b.RunParallel(func(pb *testing.PB) {
522 for pb.Next() {
523 var r codeResponse
524 if err := json.Unmarshal(codeJSON, &r); err != nil {
525 b.Fatal("Unmarshal:", err)
526 }
527 }
528 })
529 b.SetBytes(int64(len(codeJSON)))
530 }
531
532 func BenchmarkCodeUnmarshalReuse(b *testing.B) {
533 b.ReportAllocs()
534 if codeJSON == nil {
535 b.StopTimer()
536 codeInit()
537 b.StartTimer()
538 }
539 b.RunParallel(func(pb *testing.PB) {
540 var r codeResponse
541 for pb.Next() {
542 if err := json.Unmarshal(codeJSON, &r); err != nil {
543 b.Fatal("Unmarshal:", err)
544 }
545 }
546 })
547 b.SetBytes(int64(len(codeJSON)))
548 }
549
550 // padded is a value alone in its cache lines. The values which the goroutines of a parallel benchmark decode
551 // into are padded: small values allocated one after another share a cache line, which the goroutines then
552 // write by turns, and how many share one depends on the run, which made the result of the same code differ
553 // by half from a run to another.
554 type padded[T any] struct {
555 _ [64]byte
556 v T
557 _ [64]byte
558 }
559
560 func newPadded[T any]() *padded[T] {
561 return new(padded[T])
562 }
563
564 func BenchmarkUnmarshalString(b *testing.B) {
565 b.ReportAllocs()
566 data := []byte(`"hello, world"`)
567 b.RunParallel(func(pb *testing.PB) {
568 s := newPadded[string]()
569 for pb.Next() {
570 if err := json.Unmarshal(data, &s.v); err != nil {
571 b.Fatal("Unmarshal:", err)
572 }
573 }
574 })
575 }
576
577 func BenchmarkUnmarshalFloat64(b *testing.B) {
578 b.ReportAllocs()
579 data := []byte(`3.14`)
580 b.RunParallel(func(pb *testing.PB) {
581 f := newPadded[float64]()
582 for pb.Next() {
583 if err := json.Unmarshal(data, &f.v); err != nil {
584 b.Fatal("Unmarshal:", err)
585 }
586 }
587 })
588 }
589
590 func BenchmarkUnmarshalInt64(b *testing.B) {
591 b.ReportAllocs()
592 data := []byte(`3`)
593 b.RunParallel(func(pb *testing.PB) {
594 x := newPadded[int64]()
595 for pb.Next() {
596 if err := json.Unmarshal(data, &x.v); err != nil {
597 b.Fatal("Unmarshal:", err)
598 }
599 }
600 })
601 }
602
603 func BenchmarkUnmarshalIssue10335(b *testing.B) {
604 b.ReportAllocs()
605 j := []byte(`{"a":{ }}`)
606 b.RunParallel(func(pb *testing.PB) {
607 var s struct{}
608 for pb.Next() {
609 if err := json.Unmarshal(j, &s); err != nil {
610 b.Fatal(err)
611 }
612 }
613 })
614 }
615
616 func BenchmarkUnmarshalUnmapped(b *testing.B) {
617 b.ReportAllocs()
618 j := []byte(`{"s": "hello", "y": 2, "o": {"x": 0}, "a": [1, 99, {"x": 1}]}`)
619 b.RunParallel(func(pb *testing.PB) {
620 var s struct{}
621 for pb.Next() {
622 if err := json.Unmarshal(j, &s); err != nil {
623 b.Fatal(err)
624 }
625 }
626 })
627 }
628
629 func Benchmark_Compact_EncodingJson(b *testing.B) {
630 b.ReportAllocs()
631 if codeJSON == nil {
632 b.StopTimer()
633 codeInit()
634 b.StartTimer()
635 }
636 for i := 0; i < b.N; i++ {
637 var buf bytes.Buffer
638 if err := stdjson.Compact(&buf, codeJSON); err != nil {
639 b.Fatal(err)
640 }
641 }
642 }
643
644 func Benchmark_Compact_GoJson(b *testing.B) {
645 b.ReportAllocs()
646 if codeJSON == nil {
647 b.StopTimer()
648 codeInit()
649 b.StartTimer()
650 }
651 for i := 0; i < b.N; i++ {
652 var buf bytes.Buffer
653 if err := json.Compact(&buf, codeJSON); err != nil {
654 b.Fatal(err)
655 }
656 }
657 }
658
659 func Benchmark_Indent_EncodingJson(b *testing.B) {
660 b.ReportAllocs()
661 if codeJSON == nil {
662 b.StopTimer()
663 codeInit()
664 b.StartTimer()
665 }
666 for i := 0; i < b.N; i++ {
667 var buf bytes.Buffer
668 if err := stdjson.Indent(&buf, codeJSON, "-", " "); err != nil {
669 b.Fatal(err)
670 }
671 }
672 }
673
674 func Benchmark_Indent_GoJson(b *testing.B) {
675 b.ReportAllocs()
676 if codeJSON == nil {
677 b.StopTimer()
678 codeInit()
679 b.StartTimer()
680 }
681 for i := 0; i < b.N; i++ {
682 var buf bytes.Buffer
683 if err := json.Indent(&buf, codeJSON, "-", " "); err != nil {
684 b.Fatal(err)
685 }
686 }
687 }
688
689 // A list of values of a recursive type, each the last field of the previous: encoded in one frame.
690 type listNode struct {
691 Id int `json:"id"`
692 Name string `json:"name"`
693 Next *listNode `json:"next"`
694 }
695
696 var linkedList = func() *listNode {
697 var head *listNode
698 for i := 100; i > 0; i-- {
699 head = &listNode{Id: i, Name: "node", Next: head}
700 }
701 return head
702 }()
703
704 func Benchmark_EncodeLinkedList_GoJson(b *testing.B) {
705 b.ReportAllocs()
706 for i := 0; i < b.N; i++ {
707 if _, err := json.Marshal(linkedList); err != nil {
708 b.Fatal("Marshal:", err)
709 }
710 }
711 }
712
713 // the recursive field is the first of the node: the option puts it last, so that the list is encoded in
714 // one frame.
715 type listNodeNextFirst struct {
716 Next *listNodeNextFirst `json:"next"`
717 Id int `json:"id"`
718 Name string `json:"name"`
719 }
720
721 var linkedListNextFirst = func() *listNodeNextFirst {
722 var head *listNodeNextFirst
723 for i := 100; i > 0; i-- {
724 head = &listNodeNextFirst{Next: head, Id: i, Name: "node"}
725 }
726 return head
727 }()
728
729 func Benchmark_EncodeLinkedListNextFirst_GoJson(b *testing.B) {
730 b.ReportAllocs()
731 for i := 0; i < b.N; i++ {
732 if _, err := json.Marshal(linkedListNextFirst); err != nil {
733 b.Fatal("Marshal:", err)
734 }
735 }
736 }
737
738 func Benchmark_EncodeLinkedListNextFirst_GoJsonOptimizedFieldOrder(b *testing.B) {
739 b.ReportAllocs()
740 for i := 0; i < b.N; i++ {
741 if _, err := json.MarshalWithOption(linkedListNextFirst, json.OptimizeFieldOrder()); err != nil {
742 b.Fatal("Marshal:", err)
743 }
744 }
745 }
746
747 func Benchmark_EncodeLinkedList_EncodingJson(b *testing.B) {
748 b.ReportAllocs()
749 for i := 0; i < b.N; i++ {
750 if _, err := stdjson.Marshal(linkedList); err != nil {
751 b.Fatal("Marshal:", err)
752 }
753 }
754 }