github.com/karrick/go@v0.0.0-20170817181416-d5b0ec858b37/test/bench/go1/json_test.go (about)

     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  
     7  package go1
     8  
     9  import (
    10  	"bytes"
    11  	"compress/bzip2"
    12  	"encoding/base64"
    13  	"encoding/json"
    14  	"io"
    15  	"io/ioutil"
    16  	"testing"
    17  )
    18  
    19  var (
    20  	jsonbytes = makeJsonBytes()
    21  	jsondata  = makeJsonData()
    22  )
    23  
    24  func makeJsonBytes() []byte {
    25  	var r io.Reader
    26  	r = bytes.NewReader(bytes.Replace(jsonbz2_base64, []byte{'\n'}, nil, -1))
    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  
    36  func makeJsonData() JSONResponse {
    37  	var v JSONResponse
    38  	if err := json.Unmarshal(jsonbytes, &v); err != nil {
    39  		panic(err)
    40  	}
    41  	return v
    42  }
    43  
    44  type JSONResponse struct {
    45  	Tree     *JSONNode `json:"tree"`
    46  	Username string    `json:"username"`
    47  }
    48  
    49  type 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  
    59  func jsondec() {
    60  	var r JSONResponse
    61  	if err := json.Unmarshal(jsonbytes, &r); err != nil {
    62  		panic(err)
    63  	}
    64  	_ = r
    65  }
    66  
    67  func jsonenc() {
    68  	buf, err := json.Marshal(&jsondata)
    69  	if err != nil {
    70  		panic(err)
    71  	}
    72  	_ = buf
    73  }
    74  
    75  func BenchmarkJSONEncode(b *testing.B) {
    76  	b.SetBytes(int64(len(jsonbytes)))
    77  	for i := 0; i < b.N; i++ {
    78  		jsonenc()
    79  	}
    80  }
    81  
    82  func BenchmarkJSONDecode(b *testing.B) {
    83  	b.SetBytes(int64(len(jsonbytes)))
    84  	for i := 0; i < b.N; i++ {
    85  		jsondec()
    86  	}
    87  }