2016-12-11 09:53:35 +02:00
|
|
|
package jsoniter
|
|
|
|
|
|
|
|
import (
|
2017-06-06 17:27:00 +02:00
|
|
|
"encoding/json"
|
2016-12-11 09:53:35 +02:00
|
|
|
"fmt"
|
2017-05-05 11:44:09 +02:00
|
|
|
"github.com/json-iterator/go/require"
|
2017-06-06 17:27:00 +02:00
|
|
|
"testing"
|
2016-12-11 09:53:35 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
func Test_bind_api_demo(t *testing.T) {
|
2017-05-05 11:44:09 +02:00
|
|
|
should := require.New(t)
|
2016-12-11 09:53:35 +02:00
|
|
|
val := []int{}
|
2017-05-05 11:44:09 +02:00
|
|
|
err := UnmarshalFromString(`[0,1,2,3] `, &val)
|
|
|
|
should.Nil(err)
|
|
|
|
should.Equal([]int{0, 1, 2, 3}, val)
|
2016-12-11 09:53:35 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func Test_iterator_api_demo(t *testing.T) {
|
2017-06-17 04:21:37 +02:00
|
|
|
iter := ParseString(ConfigDefault, `[0,1,2,3]`)
|
2016-12-11 09:53:35 +02:00
|
|
|
total := 0
|
|
|
|
for iter.ReadArray() {
|
|
|
|
total += iter.ReadInt()
|
|
|
|
}
|
|
|
|
fmt.Println(total)
|
2017-06-02 10:52:20 +02:00
|
|
|
}
|
2017-06-05 16:04:52 +02:00
|
|
|
|
|
|
|
type People struct {
|
2017-06-06 17:27:00 +02:00
|
|
|
Name string
|
|
|
|
Gender string
|
|
|
|
Age int
|
2017-06-05 16:04:52 +02:00
|
|
|
Address string
|
2017-06-06 17:27:00 +02:00
|
|
|
Mobile string
|
2017-06-05 16:04:52 +02:00
|
|
|
Country string
|
2017-06-06 17:27:00 +02:00
|
|
|
Height int
|
2017-06-05 16:04:52 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func jsoniterMarshal(p *People) error {
|
|
|
|
_, err := Marshal(p)
|
|
|
|
if nil != err {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
func stdMarshal(p *People) error {
|
|
|
|
_, err := json.Marshal(p)
|
|
|
|
if nil != err {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func BenchmarkJosniterMarshal(b *testing.B) {
|
|
|
|
var p People
|
|
|
|
p.Address = "上海市徐汇区漕宝路"
|
|
|
|
p.Age = 30
|
|
|
|
p.Country = "中国"
|
|
|
|
p.Gender = "male"
|
|
|
|
p.Height = 170
|
|
|
|
p.Mobile = "18502120533"
|
|
|
|
p.Name = "Elvin"
|
|
|
|
b.ReportAllocs()
|
|
|
|
for i := 0; i < b.N; i++ {
|
|
|
|
err := jsoniterMarshal(&p)
|
|
|
|
if nil != err {
|
|
|
|
b.Error(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func BenchmarkStdMarshal(b *testing.B) {
|
|
|
|
var p People
|
|
|
|
p.Address = "上海市徐汇区漕宝路"
|
|
|
|
p.Age = 30
|
|
|
|
p.Country = "中国"
|
|
|
|
p.Gender = "male"
|
|
|
|
p.Height = 170
|
|
|
|
p.Mobile = "18502120533"
|
|
|
|
p.Name = "Elvin"
|
|
|
|
b.ReportAllocs()
|
|
|
|
for i := 0; i < b.N; i++ {
|
|
|
|
err := stdMarshal(&p)
|
|
|
|
if nil != err {
|
|
|
|
b.Error(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|