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// This benchmark tests JSON encoding and decoding performance.
6
7package go1
8
9import (
10	"compress/bzip2"
11	"encoding/base64"
12	"encoding/json"
13	"io"
14	"io/ioutil"
15	"strings"
16	"testing"
17)
18
19var (
20	jsonbytes = makeJsonBytes()
21	jsondata  = makeJsonData()
22)
23
24func makeJsonBytes() []byte {
25	var r io.Reader
26	r = strings.NewReader(jsonbz2_base64)
27	r = base64.NewDecoder(base64.StdEncoding, r)
28	r = bzip2.NewReader(r)
29	b, err := ioutil.ReadAll(r)
30	if err != nil {
31		panic(err)
32	}
33	return b
34}
35
36func makeJsonData() JSONResponse {
37	var v JSONResponse
38	if err := json.Unmarshal(jsonbytes, &v); err != nil {
39		panic(err)
40	}
41	return v
42}
43
44type JSONResponse struct {
45	Tree     *JSONNode `json:"tree"`
46	Username string    `json:"username"`
47}
48
49type JSONNode struct {
50	Name     string      `json:"name"`
51	Kids     []*JSONNode `json:"kids"`
52	CLWeight float64     `json:"cl_weight"`
53	Touches  int         `json:"touches"`
54	MinT     int64       `json:"min_t"`
55	MaxT     int64       `json:"max_t"`
56	MeanT    int64       `json:"mean_t"`
57}
58
59func jsondec() {
60	var r JSONResponse
61	if err := json.Unmarshal(jsonbytes, &r); err != nil {
62		panic(err)
63	}
64	_ = r
65}
66
67func jsonenc() {
68	buf, err := json.Marshal(&jsondata)
69	if err != nil {
70		panic(err)
71	}
72	_ = buf
73}
74
75func BenchmarkJSONEncode(b *testing.B) {
76	b.SetBytes(int64(len(jsonbytes)))
77	for i := 0; i < b.N; i++ {
78		jsonenc()
79	}
80}
81
82func BenchmarkJSONDecode(b *testing.B) {
83	b.SetBytes(int64(len(jsonbytes)))
84	for i := 0; i < b.N; i++ {
85		jsondec()
86	}
87}
88