zerojson/zerojson_bench_test.go -rw-r--r-- 1.7 KiB View raw
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package zerojson

import (
	"io"
	"io/ioutil"
	"path/filepath"
	"strings"
	"testing"

	"github.com/stretchr/testify/require"
)

func BenchmarkZerojsonTrue(b *testing.B) {
	benchmarkInput(b, " true ")
}

func BenchmarkZerojsonFalse(b *testing.B) {
	benchmarkInput(b, " false ")
}

func BenchmarkZerojsonNull(b *testing.B) {
	benchmarkInput(b, " null ")
}

func BenchmarkZerojsonString(b *testing.B) {
	benchmarkInput(b, `"a\bcde\fghijklm\nopq\rs\t\uaB12vwxyz\"\\\/"`)
}

func BenchmarkZerojsonNumber(b *testing.B) {
	benchmarkInput(b, `123.456e+7890`)
}

func BenchmarkZerojsonSmallObject(b *testing.B) {
	benchmarkInput(b, `{"active": true, "name": "Foo Bar", "age": 42}`)
}

func BenchmarkZerojsonSmallArray(b *testing.B) {
	benchmarkInput(b, `["a string", -10.234, false, null]`)
}

func BenchmarkZerojsonDeeplyNested(b *testing.B) {
	benchmarkInput(b, strings.Repeat("[", 1_000_000)+strings.Repeat("]", 1_000_000))
}

func BenchmarkZerojsonTestdata(b *testing.B) {
	files, err := ioutil.ReadDir("testdata")
	require.NoError(b, err)
	for _, file := range files {
		if ext := filepath.Ext(file.Name()); ext != ".json" {
			continue
		}

		b.Run(file.Name(), func(b *testing.B) {
			input, err := ioutil.ReadFile(filepath.Join("testdata", file.Name()))
			require.NoError(b, err)
			benchmarkInput(b, string(input))
		})
	}
}

func benchmarkInput(b *testing.B, input string) {
	p := parser{
		input: []byte(input),
		emit: func(offset int, typ byte, v []byte, err error) error {
			//fmt.Printf("[%c] %v\n", typ, string(v))
			if err == io.EOF {
				return nil
			}
			return err
		},
	}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		p.stack = stack{}
		if err := p.parse(); err != nil {
			b.Fatal(err)
		}
	}
}