...
Run Format

Source file src/encoding/json/bench_test.go

Documentation: encoding/json

     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  // Large data benchmark.
     6  // The JSON data is a summary of agl's changes in the
     7  // go, webkit, and chromium open source projects.
     8  // We benchmark converting between the JSON form
     9  // and in-memory data structures.
    10  
    11  package json
    12  
    13  import (
    14  	"bytes"
    15  	"compress/gzip"
    16  	"fmt"
    17  	"internal/testenv"
    18  	"io/ioutil"
    19  	"os"
    20  	"reflect"
    21  	"runtime"
    22  	"strings"
    23  	"sync"
    24  	"testing"
    25  )
    26  
    27  type codeResponse struct {
    28  	Tree     *codeNode `json:"tree"`
    29  	Username string    `json:"username"`
    30  }
    31  
    32  type codeNode struct {
    33  	Name     string      `json:"name"`
    34  	Kids     []*codeNode `json:"kids"`
    35  	CLWeight float64     `json:"cl_weight"`
    36  	Touches  int         `json:"touches"`
    37  	MinT     int64       `json:"min_t"`
    38  	MaxT     int64       `json:"max_t"`
    39  	MeanT    int64       `json:"mean_t"`
    40  }
    41  
    42  var codeJSON []byte
    43  var codeStruct codeResponse
    44  
    45  func codeInit() {
    46  	f, err := os.Open("testdata/code.json.gz")
    47  	if err != nil {
    48  		panic(err)
    49  	}
    50  	defer f.Close()
    51  	gz, err := gzip.NewReader(f)
    52  	if err != nil {
    53  		panic(err)
    54  	}
    55  	data, err := ioutil.ReadAll(gz)
    56  	if err != nil {
    57  		panic(err)
    58  	}
    59  
    60  	codeJSON = data
    61  
    62  	if err := Unmarshal(codeJSON, &codeStruct); err != nil {
    63  		panic("unmarshal code.json: " + err.Error())
    64  	}
    65  
    66  	if data, err = Marshal(&codeStruct); err != nil {
    67  		panic("marshal code.json: " + err.Error())
    68  	}
    69  
    70  	if !bytes.Equal(data, codeJSON) {
    71  		println("different lengths", len(data), len(codeJSON))
    72  		for i := 0; i < len(data) && i < len(codeJSON); i++ {
    73  			if data[i] != codeJSON[i] {
    74  				println("re-marshal: changed at byte", i)
    75  				println("orig: ", string(codeJSON[i-10:i+10]))
    76  				println("new: ", string(data[i-10:i+10]))
    77  				break
    78  			}
    79  		}
    80  		panic("re-marshal code.json: different result")
    81  	}
    82  }
    83  
    84  func BenchmarkCodeEncoder(b *testing.B) {
    85  	if codeJSON == nil {
    86  		b.StopTimer()
    87  		codeInit()
    88  		b.StartTimer()
    89  	}
    90  	b.RunParallel(func(pb *testing.PB) {
    91  		enc := NewEncoder(ioutil.Discard)
    92  		for pb.Next() {
    93  			if err := enc.Encode(&codeStruct); err != nil {
    94  				b.Fatal("Encode:", err)
    95  			}
    96  		}
    97  	})
    98  	b.SetBytes(int64(len(codeJSON)))
    99  }
   100  
   101  func BenchmarkCodeMarshal(b *testing.B) {
   102  	if codeJSON == nil {
   103  		b.StopTimer()
   104  		codeInit()
   105  		b.StartTimer()
   106  	}
   107  	b.RunParallel(func(pb *testing.PB) {
   108  		for pb.Next() {
   109  			if _, err := Marshal(&codeStruct); err != nil {
   110  				b.Fatal("Marshal:", err)
   111  			}
   112  		}
   113  	})
   114  	b.SetBytes(int64(len(codeJSON)))
   115  }
   116  
   117  func BenchmarkCodeDecoder(b *testing.B) {
   118  	if codeJSON == nil {
   119  		b.StopTimer()
   120  		codeInit()
   121  		b.StartTimer()
   122  	}
   123  	b.RunParallel(func(pb *testing.PB) {
   124  		var buf bytes.Buffer
   125  		dec := NewDecoder(&buf)
   126  		var r codeResponse
   127  		for pb.Next() {
   128  			buf.Write(codeJSON)
   129  			// hide EOF
   130  			buf.WriteByte('\n')
   131  			buf.WriteByte('\n')
   132  			buf.WriteByte('\n')
   133  			if err := dec.Decode(&r); err != nil {
   134  				b.Fatal("Decode:", err)
   135  			}
   136  		}
   137  	})
   138  	b.SetBytes(int64(len(codeJSON)))
   139  }
   140  
   141  func BenchmarkUnicodeDecoder(b *testing.B) {
   142  	j := []byte(`"\uD83D\uDE01"`)
   143  	b.SetBytes(int64(len(j)))
   144  	r := bytes.NewReader(j)
   145  	dec := NewDecoder(r)
   146  	var out string
   147  	b.ResetTimer()
   148  	for i := 0; i < b.N; i++ {
   149  		if err := dec.Decode(&out); err != nil {
   150  			b.Fatal("Decode:", err)
   151  		}
   152  		r.Seek(0, 0)
   153  	}
   154  }
   155  
   156  func BenchmarkDecoderStream(b *testing.B) {
   157  	b.StopTimer()
   158  	var buf bytes.Buffer
   159  	dec := NewDecoder(&buf)
   160  	buf.WriteString(`"` + strings.Repeat("x", 1000000) + `"` + "\n\n\n")
   161  	var x interface{}
   162  	if err := dec.Decode(&x); err != nil {
   163  		b.Fatal("Decode:", err)
   164  	}
   165  	ones := strings.Repeat(" 1\n", 300000) + "\n\n\n"
   166  	b.StartTimer()
   167  	for i := 0; i < b.N; i++ {
   168  		if i%300000 == 0 {
   169  			buf.WriteString(ones)
   170  		}
   171  		x = nil
   172  		if err := dec.Decode(&x); err != nil || x != 1.0 {
   173  			b.Fatalf("Decode: %v after %d", err, i)
   174  		}
   175  	}
   176  }
   177  
   178  func BenchmarkCodeUnmarshal(b *testing.B) {
   179  	if codeJSON == nil {
   180  		b.StopTimer()
   181  		codeInit()
   182  		b.StartTimer()
   183  	}
   184  	b.RunParallel(func(pb *testing.PB) {
   185  		for pb.Next() {
   186  			var r codeResponse
   187  			if err := Unmarshal(codeJSON, &r); err != nil {
   188  				b.Fatal("Unmarshal:", err)
   189  			}
   190  		}
   191  	})
   192  	b.SetBytes(int64(len(codeJSON)))
   193  }
   194  
   195  func BenchmarkCodeUnmarshalReuse(b *testing.B) {
   196  	if codeJSON == nil {
   197  		b.StopTimer()
   198  		codeInit()
   199  		b.StartTimer()
   200  	}
   201  	b.RunParallel(func(pb *testing.PB) {
   202  		var r codeResponse
   203  		for pb.Next() {
   204  			if err := Unmarshal(codeJSON, &r); err != nil {
   205  				b.Fatal("Unmarshal:", err)
   206  			}
   207  		}
   208  	})
   209  	// TODO(bcmills): Is there a missing b.SetBytes here?
   210  }
   211  
   212  func BenchmarkUnmarshalString(b *testing.B) {
   213  	data := []byte(`"hello, world"`)
   214  	b.RunParallel(func(pb *testing.PB) {
   215  		var s string
   216  		for pb.Next() {
   217  			if err := Unmarshal(data, &s); err != nil {
   218  				b.Fatal("Unmarshal:", err)
   219  			}
   220  		}
   221  	})
   222  }
   223  
   224  func BenchmarkUnmarshalFloat64(b *testing.B) {
   225  	data := []byte(`3.14`)
   226  	b.RunParallel(func(pb *testing.PB) {
   227  		var f float64
   228  		for pb.Next() {
   229  			if err := Unmarshal(data, &f); err != nil {
   230  				b.Fatal("Unmarshal:", err)
   231  			}
   232  		}
   233  	})
   234  }
   235  
   236  func BenchmarkUnmarshalInt64(b *testing.B) {
   237  	data := []byte(`3`)
   238  	b.RunParallel(func(pb *testing.PB) {
   239  		var x int64
   240  		for pb.Next() {
   241  			if err := Unmarshal(data, &x); err != nil {
   242  				b.Fatal("Unmarshal:", err)
   243  			}
   244  		}
   245  	})
   246  }
   247  
   248  func BenchmarkIssue10335(b *testing.B) {
   249  	b.ReportAllocs()
   250  	j := []byte(`{"a":{ }}`)
   251  	b.RunParallel(func(pb *testing.PB) {
   252  		var s struct{}
   253  		for pb.Next() {
   254  			if err := Unmarshal(j, &s); err != nil {
   255  				b.Fatal(err)
   256  			}
   257  		}
   258  	})
   259  }
   260  
   261  func BenchmarkUnmapped(b *testing.B) {
   262  	b.ReportAllocs()
   263  	j := []byte(`{"s": "hello", "y": 2, "o": {"x": 0}, "a": [1, 99, {"x": 1}]}`)
   264  	b.RunParallel(func(pb *testing.PB) {
   265  		var s struct{}
   266  		for pb.Next() {
   267  			if err := Unmarshal(j, &s); err != nil {
   268  				b.Fatal(err)
   269  			}
   270  		}
   271  	})
   272  }
   273  
   274  func BenchmarkTypeFieldsCache(b *testing.B) {
   275  	var maxTypes int = 1e6
   276  	if testenv.Builder() != "" {
   277  		maxTypes = 1e3 // restrict cache sizes on builders
   278  	}
   279  
   280  	// Dynamically generate many new types.
   281  	types := make([]reflect.Type, maxTypes)
   282  	fs := []reflect.StructField{{
   283  		Type:  reflect.TypeOf(""),
   284  		Index: []int{0},
   285  	}}
   286  	for i := range types {
   287  		fs[0].Name = fmt.Sprintf("TypeFieldsCache%d", i)
   288  		types[i] = reflect.StructOf(fs)
   289  	}
   290  
   291  	// clearClear clears the cache. Other JSON operations, must not be running.
   292  	clearCache := func() {
   293  		fieldCache = sync.Map{}
   294  	}
   295  
   296  	// MissTypes tests the performance of repeated cache misses.
   297  	// This measures the time to rebuild a cache of size nt.
   298  	for nt := 1; nt <= maxTypes; nt *= 10 {
   299  		ts := types[:nt]
   300  		b.Run(fmt.Sprintf("MissTypes%d", nt), func(b *testing.B) {
   301  			nc := runtime.GOMAXPROCS(0)
   302  			for i := 0; i < b.N; i++ {
   303  				clearCache()
   304  				var wg sync.WaitGroup
   305  				for j := 0; j < nc; j++ {
   306  					wg.Add(1)
   307  					go func(j int) {
   308  						for _, t := range ts[(j*len(ts))/nc : ((j+1)*len(ts))/nc] {
   309  							cachedTypeFields(t)
   310  						}
   311  						wg.Done()
   312  					}(j)
   313  				}
   314  				wg.Wait()
   315  			}
   316  		})
   317  	}
   318  
   319  	// HitTypes tests the performance of repeated cache hits.
   320  	// This measures the average time of each cache lookup.
   321  	for nt := 1; nt <= maxTypes; nt *= 10 {
   322  		// Pre-warm a cache of size nt.
   323  		clearCache()
   324  		for _, t := range types[:nt] {
   325  			cachedTypeFields(t)
   326  		}
   327  		b.Run(fmt.Sprintf("HitTypes%d", nt), func(b *testing.B) {
   328  			b.RunParallel(func(pb *testing.PB) {
   329  				for pb.Next() {
   330  					cachedTypeFields(types[0])
   331  				}
   332  			})
   333  		})
   334  	}
   335  }
   336  

View as plain text