Debian Codegraph @

benchmarks/report_test.go

raw
1 package benchmark
2
3 import (
4 "bytes"
5 stdjson "encoding/json"
6 "flag"
7 "fmt"
8 "os"
9 "reflect"
10 "regexp"
11 "runtime"
12 "runtime/debug"
13 "sort"
14 "strconv"
15 "strings"
16 "testing"
17 "time"
18
19 "benchmark/report"
20
21 "github.com/bytedance/sonic"
22 gojson "github.com/goccy/go-json"
23 jsoniter "github.com/json-iterator/go"
24 segmentio "github.com/segmentio/encoding/json"
25 )
26
27 // The benchmark report compares the JSON libraries of Go doing the same work. It is run by TestReport when
28 // BENCH_REPORT_OUT names the file to write the results to ( see the Makefile and the workflow of the report ).
29 //
30 // A comparison is fair only between configurations which do the same work, so the results are shown by category of
31 // behavior, and every library is in every category:
32 //
33 // - "std" behaves as encoding/json: HTML is escaped, the keys of a map are sorted, invalid UTF-8 is replaced,
34 // what a Marshaler returns is validated and compacted, the decoded strings are copies of the input, the
35 // skipped values are validated, and the keys match the fields regardless of case.
36 // - "fast" drops only what a program may do without: HTML is not escaped, the keys of a map are in any order,
37 // and the decoded strings may refer to the input. Everything else is as in "std".
38 // - "v2" behaves as encoding/json/v2 with its default options ( report_v2_test.go, where Go has it ).
39 // - "fastest" is every library with the options which make it fastest, whatever they drop: its probes show what
40 // each of them does differently from encoding/json.
41 //
42 // In a category, a library is configured by its options to behave as the category requires, as far as its
43 // options allow, and then as fast as they allow. A library whose options can't make it behave so is still shown,
44 // configured as close as they allow, and the report says what differs.
45 //
46 // What a category requires is checked, not assumed: every configuration is run on the probes of its category, small
47 // inputs which tell a behavior apart, and the result of every configuration on every payload is compared with the
48 // one of the baseline of the category ( see checkPayload ). A configuration which behaves differently is still
49 // measured: the report shows it apart from the others of its category, with what differs. Only an operation which
50 // fails on a payload is not measured.
51
52 // reportCategories are the categories of the configurations. The category of encoding/json/v2 is added where Go
53 // has it ( report_v2_test.go ).
54 var reportCategories = []report.Category{
55 {
56 ID: "std",
57 Title: "Same behavior as encoding/json",
58 Description: "HTML is escaped, the keys of a map are sorted, invalid UTF-8 is replaced by U+FFFD, the output of a " +
59 "Marshaler is validated and compacted, the decoded strings are copies, the values of the unknown keys are " +
60 "validated, and the keys match the fields regardless of case. The output is the same as encoding/json's, byte " +
61 "for byte.",
62 Baseline: "std/encoding/json",
63 },
64 {
65 ID: "fast",
66 Title: "Same behavior, without HTML escaping, key sorting and string copying",
67 Description: "As \"Same behavior as encoding/json\", except that HTML is not escaped, the keys of a map may be in " +
68 "any order, and the decoded strings may refer to the input, which must then not be modified while they are " +
69 "used. Invalid UTF-8 is still replaced, the output of a Marshaler is still validated, and the values of the " +
70 "unknown keys are still validated. Every library is configured as fast as its options allow in this behavior.",
71 Baseline: "fast/encoding/json",
72 },
73 {
74 ID: "fastest",
75 Title: "Every library at its fastest",
76 Description: "Every library with the options which make it fastest, whatever they make it skip. The configurations " +
77 "don't do the same work: what each of them does differently from encoding/json is listed below the charts, " +
78 "from the probes.",
79 Baseline: "fastest/encoding/json",
80 },
81 }
82
83 // reportConfig is a library called in one way.
84 type reportConfig struct {
85 report.Config
86 // module is the module of the library, whose version the report shows.
87 module string
88 // marshal encodes a value.
89 marshal func(v any) ([]byte, error)
90 // unmarshal returns the function which decodes the data into a value: what it prepares, as the string
91 // sonic decodes from, is made once, outside of the measured loop.
92 unmarshal func(data []byte) func(v any) error
93 // decodeOf is set for go-json's UnmarshalOf, which takes the value by its type: the options it is called with.
94 decodeOf []gojson.DecodeOptionFunc
95 }
96
97 func stdUnmarshal(f func([]byte, any) error) func([]byte) func(any) error {
98 return func(data []byte) func(any) error {
99 return func(v any) error { return f(data, v) }
100 }
101 }
102
103 // sonicStringUnmarshal decodes by sonic from a string, as it is at its fastest: the string is made once.
104 func sonicStringUnmarshal(api sonic.API) func([]byte) func(any) error {
105 return func(data []byte) func(any) error {
106 s := string(data)
107 return func(v any) error { return api.UnmarshalFromString(s, v) }
108 }
109 }
110
111 // stdMarshalNoHTMLEscape encodes as json.Marshal does without HTML escaping, which encoding/json does only by an
112 // Encoder: its newline is dropped.
113 func stdMarshalNoHTMLEscape(v any) ([]byte, error) {
114 var b bytes.Buffer
115 enc := stdjson.NewEncoder(&b)
116 enc.SetEscapeHTML(false)
117 if err := enc.Encode(v); err != nil {
118 return nil, err
119 }
120 return bytes.TrimSuffix(b.Bytes(), []byte{'\n'}), nil
121 }
122
123 func goJSONMarshal(opts ...gojson.EncodeOptionFunc) func(any) ([]byte, error) {
124 return func(v any) ([]byte, error) { return gojson.MarshalWithOption(v, opts...) }
125 }
126
127 func goJSONUnmarshal(opts ...gojson.DecodeOptionFunc) func([]byte) func(any) error {
128 return stdUnmarshal(func(data []byte, v any) error { return gojson.UnmarshalWithOption(data, v, opts...) })
129 }
130
131 func segmentioMarshal(flags segmentio.AppendFlags) func(any) ([]byte, error) {
132 return func(v any) ([]byte, error) { return segmentio.Append(nil, v, flags) }
133 }
134
135 func segmentioUnmarshal(flags segmentio.ParseFlags) func([]byte) func(any) error {
136 return stdUnmarshal(func(data []byte, v any) error {
137 rest, err := segmentio.Parse(data, v, flags)
138 if err == nil && len(bytes.TrimSpace(rest)) != 0 {
139 return fmt.Errorf("invalid character after top-level value")
140 }
141 return err
142 })
143 }
144
145 const (
146 goJSONModule = "github.com/goccy/go-json"
147 sonicModule = "github.com/bytedance/sonic"
148 jsoniterModule = "github.com/json-iterator/go"
149 segmentioModule = "github.com/segmentio/encoding"
150 )
151
152 // reportConfigs are the configurations measured, by category; the first of a category is its baseline. The
153 // configurations of encoding/json/v2 are added where Go has it ( report_v2_test.go ).
154 var reportConfigs = []*reportConfig{
155 // std
156 {
157 Config: report.Config{ID: "std/encoding/json", Library: "encoding/json", Category: "std", Title: "encoding/json",
158 Setting: "json.Marshal / json.Unmarshal"},
159 module: "std", marshal: stdjson.Marshal, unmarshal: stdUnmarshal(stdjson.Unmarshal),
160 },
161 {
162 Config: report.Config{ID: "std/go-json", Library: "goccy/go-json", Category: "std", Title: "goccy/go-json",
163 Setting: "json.Marshal / json.Unmarshal"},
164 module: goJSONModule, marshal: gojson.Marshal, unmarshal: stdUnmarshal(gojson.Unmarshal),
165 },
166 {
167 Config: report.Config{ID: "std/go-json/of", Library: "goccy/go-json", Category: "std", Title: "goccy/go-json ( UnmarshalOf )",
168 Setting: "json.UnmarshalOf, which takes the value by its type ( decode only )"},
169 module: goJSONModule, decodeOf: []gojson.DecodeOptionFunc{},
170 },
171 {
172 Config: report.Config{ID: "std/sonic", Library: "bytedance/sonic", Category: "std", Title: "bytedance/sonic",
173 Setting: "sonic.ConfigStd"},
174 module: sonicModule, marshal: sonic.ConfigStd.Marshal, unmarshal: stdUnmarshal(sonic.ConfigStd.Unmarshal),
175 },
176 {
177 Config: report.Config{ID: "std/jsoniter", Library: "json-iterator/go", Category: "std", Title: "json-iterator/go",
178 Setting: "jsoniter.ConfigCompatibleWithStandardLibrary"},
179 module: jsoniterModule, marshal: jsoniter.ConfigCompatibleWithStandardLibrary.Marshal,
180 unmarshal: stdUnmarshal(jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal),
181 },
182 {
183 Config: report.Config{ID: "std/segmentio", Library: "segmentio/encoding", Category: "std", Title: "segmentio/encoding",
184 Setting: "json.Marshal / json.Unmarshal"},
185 module: segmentioModule, marshal: segmentio.Marshal, unmarshal: stdUnmarshal(segmentio.Unmarshal),
186 },
187
188 // fast
189 {
190 Config: report.Config{ID: "fast/encoding/json", Library: "encoding/json", Category: "fast", Title: "encoding/json",
191 Setting: "json.Encoder with SetEscapeHTML( false ) / json.Unmarshal ( the keys of a map are always sorted and the strings copied )"},
192 module: "std", marshal: stdMarshalNoHTMLEscape, unmarshal: stdUnmarshal(stdjson.Unmarshal),
193 },
194 {
195 Config: report.Config{ID: "fast/go-json", Library: "goccy/go-json", Category: "fast", Title: "goccy/go-json",
196 Setting: "json.MarshalWithOption( DisableHTMLEscape, UnorderedMap ) / json.UnmarshalWithOption( DecodeNoCopyString )"},
197 module: goJSONModule,
198 marshal: goJSONMarshal(gojson.DisableHTMLEscape(), gojson.UnorderedMap()),
199 unmarshal: goJSONUnmarshal(gojson.DecodeNoCopyString()),
200 },
201 {
202 Config: report.Config{ID: "fast/go-json/of", Library: "goccy/go-json", Category: "fast", Title: "goccy/go-json ( UnmarshalOf )",
203 Setting: "json.UnmarshalOf( DecodeNoCopyString ), which takes the value by its type ( decode only )"},
204 module: goJSONModule, decodeOf: []gojson.DecodeOptionFunc{gojson.DecodeNoCopyString()},
205 },
206 {
207 Config: report.Config{ID: "fast/sonic", Library: "bytedance/sonic", Category: "fast", Title: "bytedance/sonic",
208 Setting: "sonic.Config{ CompactMarshaler: true, ValidateString: true }; decoded from a string ( UnmarshalFromString )"},
209 module: sonicModule, marshal: sonicFast.Marshal, unmarshal: sonicStringUnmarshal(sonicFast),
210 },
211 {
212 Config: report.Config{ID: "fast/jsoniter", Library: "json-iterator/go", Category: "fast", Title: "json-iterator/go",
213 Setting: "jsoniter.Config{ EscapeHTML: false, SortMapKeys: false, ValidateJsonRawMessage: true }"},
214 module: jsoniterModule, marshal: jsoniterFast.Marshal, unmarshal: stdUnmarshal(jsoniterFast.Unmarshal),
215 },
216 {
217 Config: report.Config{ID: "fast/segmentio", Library: "segmentio/encoding", Category: "fast", Title: "segmentio/encoding",
218 Setting: "json.Append( 0 ) / json.Parse( ZeroCopy )"},
219 module: segmentioModule, marshal: segmentioMarshal(0), unmarshal: segmentioUnmarshal(segmentio.ZeroCopy),
220 },
221 }
222
223 // the configurations of "fastest"
224 func init() {
225 reportConfigs = append(reportConfigs,
226 &reportConfig{
227 Config: report.Config{ID: "fastest/encoding/json", Library: "encoding/json", Category: "fastest", Title: "encoding/json",
228 Setting: "json.Encoder with SetEscapeHTML( false ) / json.Unmarshal"},
229 module: "std", marshal: stdMarshalNoHTMLEscape, unmarshal: stdUnmarshal(stdjson.Unmarshal),
230 },
231 &reportConfig{
232 Config: report.Config{ID: "fastest/go-json", Library: "goccy/go-json", Category: "fastest", Title: "goccy/go-json",
233 Setting: "json.MarshalWithOption( DisableHTMLEscape, DisableNormalizeUTF8, UnorderedMap ) / json.UnmarshalOf( DecodeNoCopyString )"},
234 module: goJSONModule,
235 marshal: goJSONMarshal(gojson.DisableHTMLEscape(), gojson.DisableNormalizeUTF8(), gojson.UnorderedMap()),
236 // DecodeFieldPriorityFirstWin is not set: it is faster only for an object whose fields are all decoded before its
237 // end, and a little slower on most of these payloads.
238 decodeOf: []gojson.DecodeOptionFunc{gojson.DecodeNoCopyString()},
239 },
240 &reportConfig{
241 Config: report.Config{ID: "fastest/sonic", Library: "bytedance/sonic", Category: "fastest", Title: "bytedance/sonic",
242 Setting: "sonic.ConfigFastest; decoded from a string ( UnmarshalFromString )"},
243 module: sonicModule, marshal: sonic.ConfigFastest.Marshal, unmarshal: sonicStringUnmarshal(sonic.ConfigFastest),
244 },
245 &reportConfig{
246 Config: report.Config{ID: "fastest/jsoniter", Library: "json-iterator/go", Category: "fastest", Title: "json-iterator/go",
247 Setting: "jsoniter.ConfigFastest"},
248 module: jsoniterModule, marshal: jsoniter.ConfigFastest.Marshal, unmarshal: stdUnmarshal(jsoniter.ConfigFastest.Unmarshal),
249 },
250 &reportConfig{
251 Config: report.Config{ID: "fastest/segmentio", Library: "segmentio/encoding", Category: "fastest", Title: "segmentio/encoding",
252 Setting: "json.Append( TrustRawMessage ) / json.Parse( ZeroCopy )"},
253 module: segmentioModule, marshal: segmentioMarshal(segmentio.TrustRawMessage), unmarshal: segmentioUnmarshal(segmentio.ZeroCopy),
254 },
255 )
256 }
257
258 var (
259 jsoniterFast = jsoniter.Config{EscapeHTML: false, SortMapKeys: false, ValidateJsonRawMessage: true}.Froze()
260 sonicFast = sonic.Config{CompactMarshaler: true, ValidateString: true}.Froze()
261 )
262
263 // reportPayload is an input of the benchmarks, decoded into its Go type T.
264 type reportPayload struct {
265 report.Payload
266 data []byte
267 // newValue returns a pointer to a new zero value of T.
268 newValue func() any
269 // decodeOf decodes the data into a new value of T by go-json's UnmarshalOf.
270 decodeOf func(opts []gojson.DecodeOptionFunc) error
271 // value is a pointer to the value of the data, decoded by encoding/json, which the encoders encode.
272 value any
273 }
274
275 func newReportPayload[T any](id, title, description string, data []byte) *reportPayload {
276 v := new(T)
277 if err := stdjson.Unmarshal(data, v); err != nil {
278 panic(fmt.Sprintf("%s: %v", id, err))
279 }
280 return &reportPayload{
281 Payload: report.Payload{ID: id, Title: title, Description: description, Bytes: len(data)},
282 data: data,
283 newValue: func() any { return new(T) },
284 decodeOf: func(opts []gojson.DecodeOptionFunc) error {
285 var v T
286 return gojson.UnmarshalOf(data, &v, opts...)
287 },
288 value: v,
289 }
290 }
291
292 func reportPayloads() []*reportPayload {
293 codeInit()
294 return []*reportPayload{
295 newReportPayload[SmallPayload]("small", "Small struct", "A flat struct of 9 fields.", SmallFixture),
296 newReportPayload[MediumPayload]("medium", "Medium struct", "Nested structs and a slice of structs.", MediumFixture),
297 newReportPayload[LargePayload]("large", "Large struct", "Slices of many small structs.", LargeFixture),
298 newReportPayload[TwitterStruct]("twitter", "Twitter ( struct )", "A Twitter search result, into its struct ( the payload of sonic's benchmarks ).", []byte(TwitterJson)),
299 newReportPayload[any]("twitter-any", "Twitter ( interface{} )", "The same Twitter search result, into interface{}.", []byte(TwitterJson)),
300 newReportPayload[[]*GitHubIssue]("github", "GitHub REST issues", "A page of issues of the GitHub REST API.", githubRESTIssues),
301 newReportPayload[Response]("openai", "OpenAI Responses", "A response of the OpenAI Responses API, with long escaped strings.", openAIResponsesResponseJSON),
302 newReportPayload[MessagesResponse]("anthropic", "Anthropic Messages", "A response of the Anthropic Messages API, with text and tool use blocks.", anthropicResponseJSON),
303 newReportPayload[codeResponse]("code", "Go source tree", "The large tree of encoding/json's own benchmark ( 1.9 MB ).", codeJSON),
304 }
305 }
306
307 // reportConditions are the conditions the benchmarks are measured in.
308 var reportConditions = []report.Condition{
309 {
310 ID: "live-heap",
311 Title: "With a live heap of 64 MB",
312 Description: "The process keeps 64 MB alive, as a real program keeps its own data: the GC runs as often for every " +
313 "library, since its goal is twice the live heap.",
314 },
315 {
316 ID: "no-live-heap",
317 Title: "Without a live heap",
318 Description: "The process keeps nothing alive but what the libraries keep, as their caches and pools: a library " +
319 "which keeps more is collected less often, which a real program doesn't see.",
320 },
321 }
322
323 func TestReport(t *testing.T) {
324 out := os.Getenv("BENCH_REPORT_OUT")
325 if out == "" {
326 t.Skip("BENCH_REPORT_OUT is not set")
327 }
328 rounds := 3
329 if n, err := strconv.Atoi(os.Getenv("BENCH_REPORT_ROUNDS")); err == nil && n > 0 {
330 rounds = n
331 }
332 // BENCH_REPORT_ONLY measures only the configurations, operations and payloads whose "config/op/payload" it
333 // matches, to look into a result.
334 var only *regexp.Regexp
335 if expr := os.Getenv("BENCH_REPORT_ONLY"); expr != "" {
336 only = regexp.MustCompile(expr)
337 }
338 pretouchSonic()
339 payloads := reportPayloads()
340 run := &report.Run{
341 GeneratedAt: time.Now().UTC(),
342 GoVersion: runtime.Version(),
343 GOOS: runtime.GOOS,
344 GOARCH: runtime.GOARCH,
345 CPU: reportCPU(),
346 CPUFeatures: reportCPUFeatures(),
347 Commit: os.Getenv("GITHUB_SHA"),
348 Repository: os.Getenv("GITHUB_REPOSITORY"),
349 Rounds: rounds,
350 Categories: reportCategories,
351 Conditions: reportConditions,
352 Libraries: reportLibraries(),
353 }
354 if f := flag.Lookup("test.benchtime"); f != nil {
355 run.BenchTime = f.Value.String()
356 }
357 if os.Getenv("GITHUB_RUN_ID") != "" {
358 run.RunURL = os.Getenv("GITHUB_SERVER_URL") + "/" + os.Getenv("GITHUB_REPOSITORY") + "/actions/runs/" + os.Getenv("GITHUB_RUN_ID")
359 }
360 for _, p := range payloads {
361 run.Payloads = append(run.Payloads, p.Payload)
362 }
363
364 // the configurations which pass the probes of their category, and the payloads each of them is measured on
365 type job struct {
366 op string
367 p *reportPayload
368 c *reportConfig
369 sample []testing.BenchmarkResult
370 }
371 var jobs []*job
372 for _, c := range reportConfigs {
373 run.Configs = append(run.Configs, c.Config)
374 run.Probes = append(run.Probes, runProbes(c)...)
375 for _, op := range []string{report.OpEncode, report.OpDecode} {
376 if !c.does(op) {
377 continue
378 }
379 for _, p := range payloads {
380 diff, err := checkPayload(c, op, p)
381 if err != nil {
382 run.Exclusions = append(run.Exclusions, report.Exclusion{Op: op, Payload: p.ID, Config: c.ID, Reason: err.Error()})
383 continue
384 }
385 if diff != "" {
386 run.Differences = append(run.Differences, report.Exclusion{Op: op, Payload: p.ID, Config: c.ID, Reason: diff})
387 }
388 if only != nil && !only.MatchString(c.ID+"/"+op+"/"+p.ID) {
389 continue
390 }
391 jobs = append(jobs, &job{op: op, p: p, c: c})
392 }
393 }
394 }
395
396 for _, cond := range reportConditions {
397 if cond.ID == "live-heap" {
398 liveHeap = make([]byte, 64<<20)
399 } else {
400 liveHeap = nil
401 }
402 runtime.GC()
403 for _, j := range jobs {
404 j.sample = j.sample[:0]
405 }
406 // the configurations are measured by turns, in rounds, so that a change of the machine during the run
407 // affects all of them alike; the median of the rounds is reported.
408 for round := 0; round < rounds; round++ {
409 for i := range jobs {
410 j := jobs[(i+round*len(jobs)/rounds)%len(jobs)]
411 j.sample = append(j.sample, measure(j.c, j.op, j.p))
412 }
413 }
414 for _, j := range jobs {
415 m := median(j.sample)
416 run.Results = append(run.Results, report.Result{
417 Condition: cond.ID, Op: j.op, Payload: j.p.ID, Config: j.c.ID,
418 NsPerOp: float64(m.T.Nanoseconds()) / float64(m.N),
419 BytesPerOp: m.AllocedBytesPerOp(),
420 AllocsPerOp: m.AllocsPerOp(),
421 })
422 }
423 }
424 liveHeap = nil
425 if err := report.WriteRun(out, run); err != nil {
426 t.Fatal(err)
427 }
428 }
429
430 // does reports whether the configuration does the operation.
431 func (c *reportConfig) does(op string) bool {
432 if op == report.OpEncode {
433 return c.marshal != nil
434 }
435 return c.unmarshal != nil || c.decodeOf != nil
436 }
437
438 // measure measures the configuration on the payload.
439 func measure(c *reportConfig, op string, p *reportPayload) testing.BenchmarkResult {
440 return testing.Benchmark(func(b *testing.B) {
441 b.ReportAllocs()
442 b.SetBytes(int64(len(p.data)))
443 switch {
444 case op == report.OpEncode:
445 for i := 0; i < b.N; i++ {
446 if _, err := c.marshal(p.value); err != nil {
447 b.Fatal(err)
448 }
449 }
450 case c.decodeOf != nil:
451 for i := 0; i < b.N; i++ {
452 if err := p.decodeOf(c.decodeOf); err != nil {
453 b.Fatal(err)
454 }
455 }
456 default:
457 unmarshal := c.unmarshal(p.data)
458 b.ResetTimer()
459 for i := 0; i < b.N; i++ {
460 if err := unmarshal(p.newValue()); err != nil {
461 b.Fatal(err)
462 }
463 }
464 }
465 })
466 }
467
468 func median(rs []testing.BenchmarkResult) testing.BenchmarkResult {
469 sort.Slice(rs, func(i, j int) bool { return nsPerOp(rs[i]) < nsPerOp(rs[j]) })
470 return rs[len(rs)/2]
471 }
472
473 func nsPerOp(r testing.BenchmarkResult) float64 {
474 return float64(r.T.Nanoseconds()) / float64(r.N)
475 }
476
477 // baselineOf returns the baseline of the category.
478 func baselineOf(category string) *reportConfig {
479 for _, cat := range reportCategories {
480 if cat.ID != category {
481 continue
482 }
483 for _, c := range reportConfigs {
484 if c.ID == cat.Baseline {
485 return c
486 }
487 }
488 }
489 panic("no baseline of " + category)
490 }
491
492 // checkPayload returns how the result of the configuration on the payload differs from the one of the baseline of
493 // its category, or "", and the error of the operation, which then can't be measured: a decoded value must be the
494 // one the baseline decodes; an encoded value must be the baseline's output byte for byte in "std", where the
495 // output is defined byte for byte, and the same JSON value in the other categories.
496 func checkPayload(c *reportConfig, op string, p *reportPayload) (string, error) {
497 base := baselineOf(c.Category)
498 if op == report.OpDecode {
499 v := p.newValue()
500 var err error
501 if c.decodeOf != nil {
502 // UnmarshalOf decodes the value as Unmarshal does: it is checked by a decode into the value.
503 err = gojson.UnmarshalWithOption(p.data, v, c.decodeOf...)
504 } else {
505 err = c.unmarshal(p.data)(v)
506 }
507 if err != nil || c == base {
508 return "", err
509 }
510 want := p.newValue()
511 if err := base.unmarshal(p.data)(want); err != nil {
512 return "", fmt.Errorf("the baseline fails: %w", err)
513 }
514 if !reflect.DeepEqual(v, want) {
515 return "the decoded value differs from " + base.Title + "'s", nil
516 }
517 return "", nil
518 }
519 got, err := c.marshal(p.value)
520 if err != nil || c == base {
521 return "", err
522 }
523 want, err := base.marshal(p.value)
524 if err != nil {
525 return "", fmt.Errorf("the baseline fails: %w", err)
526 }
527 if c.Category == "std" {
528 if !bytes.Equal(got, want) {
529 return "the output differs from " + base.Title + "'s", nil
530 }
531 } else if !sameJSON(got, want) {
532 return "the output is not the same JSON value as " + base.Title + "'s", nil
533 }
534 return "", nil
535 }
536
537 // sameJSON reports whether a and b are the same JSON value, whatever the order of the keys of their objects.
538 func sameJSON(a, b []byte) bool {
539 var x, y any
540 da, db := stdjson.NewDecoder(bytes.NewReader(a)), stdjson.NewDecoder(bytes.NewReader(b))
541 da.UseNumber()
542 db.UseNumber()
543 if da.Decode(&x) != nil || db.Decode(&y) != nil {
544 return false
545 }
546 return reflect.DeepEqual(x, y)
547 }
548
549 // reportProbe is a small input which tells a behavior apart. check returns "" if the configuration behaves as the
550 // category requires, else what it did.
551 type reportProbe struct {
552 id, description string
553 op string
554 // categories are the categories which require the behavior.
555 categories []string
556 check func(c *reportConfig) string
557 }
558
559 type probeMarshaler struct{}
560
561 func (probeMarshaler) MarshalJSON() ([]byte, error) { return []byte(`{ "a" : [ 1 , 2 ] }`), nil }
562
563 type probeFields struct {
564 Name string
565 Small int8
566 }
567
568 // encodeProbe checks that the configuration encodes v as want, or, where exact is false, as the same JSON value.
569 func encodeProbe(v any, want string, exact bool) func(c *reportConfig) string {
570 return func(c *reportConfig) string {
571 got, err := c.marshal(v)
572 if err != nil {
573 return "error: " + err.Error()
574 }
575 if exact && string(got) != want || !exact && !sameJSON(got, []byte(want)) {
576 return fmt.Sprintf("got %s, want %s", got, want)
577 }
578 return ""
579 }
580 }
581
582 // decodeProbe decodes data into a new value of newValue's type, and checks the value, or that it is an error when
583 // check is nil.
584 func decodeProbe(data string, newValue func() any, check func(v any) string) func(c *reportConfig) string {
585 return func(c *reportConfig) string {
586 v := newValue()
587 var err error
588 if c.decodeOf != nil {
589 err = gojson.UnmarshalWithOption([]byte(data), v, c.decodeOf...)
590 } else {
591 err = c.unmarshal([]byte(data))(v)
592 }
593 if check == nil {
594 if err == nil {
595 return "accepted invalid input"
596 }
597 return ""
598 }
599 if err != nil {
600 return "error: " + err.Error()
601 }
602 return check(v)
603 }
604 }
605
606 var (
607 v1Like = []string{"std", "fast"}
608 every = []string{"std", "fast", "v2"}
609 )
610
611 type probeSlice struct {
612 S []int
613 M map[string]int
614 }
615
616 func stringProbe(want string) func(v any) string {
617 return func(v any) string {
618 if s := *v.(*string); s != want {
619 return fmt.Sprintf("got %q", s)
620 }
621 return ""
622 }
623 }
624
625 func nameProbe(want string) func(v any) string {
626 return func(v any) string {
627 if n := v.(*probeFields).Name; n != want {
628 return fmt.Sprintf("got %q", n)
629 }
630 return ""
631 }
632 }
633
634 var reportProbes = []reportProbe{
635 {id: "escape-html", op: report.OpEncode, categories: []string{"std"},
636 description: `HTML characters are escaped: "<&>" is encoded as "\u003c\u0026\u003e".`,
637 check: encodeProbe("<&>", `"\u003c\u0026\u003e"`, true)},
638 {id: "no-escape-html", op: report.OpEncode, categories: []string{"v2"},
639 description: `HTML characters are not escaped: "<&>" is encoded as "<&>".`,
640 check: encodeProbe("<&>", `"<&>"`, true)},
641 {id: "sort-map-keys", op: report.OpEncode, categories: []string{"std"},
642 description: "The keys of a map are sorted.",
643 check: encodeProbe(map[string]int{"b": 1, "c": 2, "a": 3}, `{"a":3,"b":1,"c":2}`, true)},
644 {id: "invalid-utf8-encode", op: report.OpEncode, categories: v1Like,
645 description: `Invalid UTF-8 is encoded as U+FFFD.`,
646 check: encodeProbe("a\xffb", `"a\ufffdb"`, false)},
647 {id: "invalid-utf8-encode-error", op: report.OpEncode, categories: []string{"v2"},
648 description: "Invalid UTF-8 is an error when it is encoded.",
649 check: func(c *reportConfig) string {
650 if out, err := c.marshal("a\xffb"); err == nil {
651 return "encoded as " + string(out)
652 }
653 return ""
654 }},
655 {id: "nil-null", op: report.OpEncode, categories: v1Like,
656 description: "A nil slice and a nil map are encoded as null.",
657 check: encodeProbe(probeSlice{}, `{"S":null,"M":null}`, false)},
658 {id: "nil-empty", op: report.OpEncode, categories: []string{"v2"},
659 description: "A nil slice is encoded as [] and a nil map as {}.",
660 check: encodeProbe(probeSlice{}, `{"S":[],"M":{}}`, false)},
661 {id: "floats", op: report.OpEncode, categories: every,
662 description: "Floats are formatted as encoding/json formats them.",
663 check: encodeProbe([]float64{1e21, 1e20, 1e-7, 0.000001, 0.1, 123456789, -0.5}, `[1e+21,100000000000000000000,1e-7,0.000001,0.1,123456789,-0.5]`, true)},
664 {id: "marshaler-compact", op: report.OpEncode, categories: v1Like,
665 description: "The output of a Marshaler is compacted.",
666 check: encodeProbe(probeMarshaler{}, `{"a":[1,2]}`, true)},
667 {id: "invalid-utf8-decode", op: report.OpDecode, categories: v1Like,
668 description: "Invalid UTF-8 in a string is decoded as U+FFFD.",
669 check: decodeProbe("\"a\xffb\"", func() any { return new(string) }, stringProbe("a\ufffdb"))},
670 {id: "invalid-utf8-decode-error", op: report.OpDecode, categories: []string{"v2"},
671 description: "Invalid UTF-8 in a string is an error.",
672 check: decodeProbe("\"a\xffb\"", func() any { return new(string) }, nil)},
673 {id: "control-character", op: report.OpDecode, categories: every,
674 description: "A control character in a string is an error.",
675 check: decodeProbe("\"a\x01\"", func() any { return new(string) }, nil)},
676 {id: "case-insensitive", op: report.OpDecode, categories: v1Like,
677 description: "A key matches a field regardless of case.",
678 check: decodeProbe(`{"NAME":"x"}`, func() any { return new(probeFields) }, nameProbe("x"))},
679 {id: "case-sensitive", op: report.OpDecode, categories: []string{"v2"},
680 description: "A key matches a field only by its case.",
681 check: decodeProbe(`{"NAME":"x"}`, func() any { return new(probeFields) }, nameProbe(""))},
682 {id: "skipped-value-validated", op: report.OpDecode, categories: every,
683 description: "The value of an unknown key is validated.",
684 check: decodeProbe(`{"unknown":[1,,2],"Name":"x"}`, func() any { return new(probeFields) }, nil)},
685 {id: "duplicate-key", op: report.OpDecode, categories: v1Like,
686 description: "The last of duplicate keys wins.",
687 check: decodeProbe(`{"Name":"a","Name":"b"}`, func() any { return new(probeFields) }, nameProbe("b"))},
688 {id: "duplicate-key-error", op: report.OpDecode, categories: []string{"v2"},
689 description: "Duplicate keys are an error.",
690 check: decodeProbe(`{"Name":"a","Name":"b"}`, func() any { return new(probeFields) }, nil)},
691 {id: "overflow", op: report.OpDecode, categories: every,
692 description: "A number out of the range of its field is an error.",
693 check: decodeProbe(`{"Small":300}`, func() any { return new(probeFields) }, nil)},
694 {id: "string-copied", op: report.OpDecode, categories: []string{"std", "v2"},
695 description: "A decoded string is a copy: it doesn't change when the input is modified.",
696 check: func(c *reportConfig) string {
697 data := []byte(`{"Name":"abcdefghijklmnopqrstuvwxyz"}`)
698 v := new(probeFields)
699 var err error
700 if c.decodeOf != nil {
701 err = gojson.UnmarshalWithOption(data, v, c.decodeOf...)
702 } else {
703 err = c.unmarshal(data)(v)
704 }
705 if err != nil {
706 return "error: " + err.Error()
707 }
708 copy(data[9:], "ZZZZ")
709 if v.Name != "abcdefghijklmnopqrstuvwxyz" {
710 return "the string refers to the input"
711 }
712 return ""
713 }},
714 }
715
716 // runProbes runs the probes of the category of the configuration.
717 func runProbes(c *reportConfig) []report.ProbeResult {
718 var rs []report.ProbeResult
719 for _, p := range reportProbes {
720 if !c.does(p.op) {
721 continue
722 }
723 required, informational := false, false
724 for _, cat := range p.categories {
725 required = required || cat == c.Category
726 // "fastest" requires nothing: the probes of encoding/json's behavior tell what each configuration skips
727 informational = informational || c.Category == "fastest" && cat == "std"
728 }
729 if !required && !informational {
730 // a probe of another category tells nothing of this one
731 continue
732 }
733 detail := safeProbe(p, c)
734 rs = append(rs, report.ProbeResult{
735 Config: c.ID, Probe: p.id, Description: p.description, Required: required, Passed: detail == "", Detail: detail,
736 })
737 }
738 return rs
739 }
740
741 // safeProbe runs a probe, reporting a panic of the library as its result.
742 func safeProbe(p reportProbe, c *reportConfig) (detail string) {
743 defer func() {
744 if r := recover(); r != nil {
745 detail = fmt.Sprintf("panic: %v", r)
746 }
747 }()
748 return p.check(c)
749 }
750
751 // reportLibraries returns the libraries measured, with the versions the benchmarks are built with.
752 func reportLibraries() []report.Library {
753 versions := map[string]string{"std": runtime.Version()}
754 if info, ok := debug.ReadBuildInfo(); ok {
755 for _, d := range info.Deps {
756 v := d.Version
757 if d.Replace != nil {
758 v = d.Replace.Version
759 }
760 versions[d.Path] = v
761 }
762 }
763 if sha := os.Getenv("GITHUB_SHA"); sha != "" {
764 // go-json is the one of the repository, replaced by its directory
765 versions["github.com/goccy/go-json"] = sha
766 }
767 seen := map[string]bool{}
768 var libs []report.Library
769 for _, c := range reportConfigs {
770 if seen[c.Library] {
771 continue
772 }
773 seen[c.Library] = true
774 v := versions[c.module]
775 if v == "" {
776 v = "(devel)"
777 }
778 libs = append(libs, report.Library{Name: c.Library, Module: c.module, Version: v})
779 }
780 return libs
781 }
782
783 // reportCPU returns the model of the CPU: BENCH_CPU, which the workflow sets, or the model in /proc/cpuinfo.
784 func reportCPU() string {
785 if cpu := os.Getenv("BENCH_CPU"); cpu != "" {
786 return cpu
787 }
788 data, err := os.ReadFile("/proc/cpuinfo")
789 if err != nil {
790 return runtime.GOARCH
791 }
792 for _, line := range strings.Split(string(data), "\n") {
793 if k, v, ok := strings.Cut(line, ":"); ok && strings.TrimSpace(k) == "model name" {
794 return strings.TrimSpace(v)
795 }
796 }
797 return runtime.GOARCH
798 }
799
800 // cpuFeatures are the extensions of the instruction set which the report shows, by their names in /proc/cpuinfo.
801 var cpuFeatures = []struct{ flag, name string }{
802 {"avx2", "AVX2"}, {"bmi2", "BMI2"}, {"avx512f", "AVX-512F"}, {"avx512bw", "AVX-512BW"}, {"avx512vl", "AVX-512VL"},
803 {"asimd", "NEON"}, {"sve", "SVE"}, {"sve2", "SVE2"},
804 }
805
806 // reportCPUFeatures returns the extensions of the instruction set of the CPU, from /proc/cpuinfo: the flags of an
807 // amd64 CPU and the features of an arm64 one.
808 func reportCPUFeatures() []string {
809 data, err := os.ReadFile("/proc/cpuinfo")
810 if err != nil {
811 return nil
812 }
813 has := map[string]bool{}
814 for _, line := range strings.Split(string(data), "\n") {
815 k, v, ok := strings.Cut(line, ":")
816 if k = strings.TrimSpace(k); !ok || k != "flags" && k != "Features" {
817 continue
818 }
819 for _, f := range strings.Fields(v) {
820 has[f] = true
821 }
822 break
823 }
824 var fs []string
825 for _, f := range cpuFeatures {
826 if has[f.flag] {
827 fs = append(fs, f.name)
828 }
829 }
830 return fs
831 }