github.com/karrick/go@v0.0.0-20170817181416-d5b0ec858b37/test/bench/go1/gob_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 gob encoding and decoding performance.
     6  
     7  package go1
     8  
     9  import (
    10  	"bytes"
    11  	"encoding/gob"
    12  	"encoding/json"
    13  	"io/ioutil"
    14  	"log"
    15  	"reflect"
    16  	"testing"
    17  )
    18  
    19  var (
    20  	gobbytes []byte
    21  	gobdata  *JSONResponse
    22  )
    23  
    24  func init() {
    25  	gobdata = gobResponse(&jsondata)
    26  
    27  	var buf bytes.Buffer
    28  	if err := gob.NewEncoder(&buf).Encode(gobdata); err != nil {
    29  		panic(err)
    30  	}
    31  	gobbytes = buf.Bytes()
    32  
    33  	var r JSONResponse
    34  	if err := gob.NewDecoder(bytes.NewBuffer(gobbytes)).Decode(&r); err != nil {
    35  		panic(err)
    36  	}
    37  	if !reflect.DeepEqual(gobdata, &r) {
    38  		log.Printf("%v\n%v", jsondata, r)
    39  		b, _ := json.Marshal(&jsondata)
    40  		br, _ := json.Marshal(&r)
    41  		log.Printf("%s\n%s\n", b, br)
    42  		panic("gob: encode+decode lost data")
    43  	}
    44  }
    45  
    46  // gob turns [] into null, so make a copy of the data structure like that
    47  func gobResponse(r *JSONResponse) *JSONResponse {
    48  	return &JSONResponse{gobNode(r.Tree), r.Username}
    49  }
    50  
    51  func gobNode(n *JSONNode) *JSONNode {
    52  	n1 := new(JSONNode)
    53  	*n1 = *n
    54  	if len(n1.Kids) == 0 {
    55  		n1.Kids = nil
    56  	} else {
    57  		for i, k := range n1.Kids {
    58  			n1.Kids[i] = gobNode(k)
    59  		}
    60  	}
    61  	return n1
    62  }
    63  
    64  func gobdec() {
    65  	if gobbytes == nil {
    66  		panic("gobdata not initialized")
    67  	}
    68  	var r JSONResponse
    69  	if err := gob.NewDecoder(bytes.NewBuffer(gobbytes)).Decode(&r); err != nil {
    70  		panic(err)
    71  	}
    72  	_ = r
    73  }
    74  
    75  func gobenc() {
    76  	if err := gob.NewEncoder(ioutil.Discard).Encode(&gobdata); err != nil {
    77  		panic(err)
    78  	}
    79  }
    80  
    81  func BenchmarkGobDecode(b *testing.B) {
    82  	b.SetBytes(int64(len(gobbytes)))
    83  	for i := 0; i < b.N; i++ {
    84  		gobdec()
    85  	}
    86  }
    87  
    88  func BenchmarkGobEncode(b *testing.B) {
    89  	b.SetBytes(int64(len(gobbytes)))
    90  	for i := 0; i < b.N; i++ {
    91  		gobenc()
    92  	}
    93  }