Source file test/bench/go1/json_test.go

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

View as plain text