~mna/zerojson

zerojson/fastjson_bench_test.go -rw-r--r-- 1.6 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
package zerojson

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

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

func BenchmarkFastjsonTrue(b *testing.B) {
	benchmarkFastjsonInput(b, " true ")
}

func BenchmarkFastjsonFalse(b *testing.B) {
	benchmarkFastjsonInput(b, " false ")
}

func BenchmarkFastjsonNull(b *testing.B) {
	benchmarkFastjsonInput(b, " null ")
}

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

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

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

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

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

func BenchmarkFastjsonTestdata(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)
			benchmarkFastjsonInput(b, string(input))
		})
	}
}

func benchmarkFastjsonInput(b *testing.B, input string) {
	var p fastjson.Parser
	for i := 0; i < b.N; i++ {
		if _, err := p.Parse(input); err != nil {
			b.Fatal(err)
		}
	}
}