jsoniter_demo_test.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package jsoniter
  2. import (
  3. "encoding/json"
  4. "testing"
  5. "github.com/stretchr/testify/require"
  6. )
  7. func Test_bind_api_demo(t *testing.T) {
  8. should := require.New(t)
  9. val := []int{}
  10. err := UnmarshalFromString(`[0,1,2,3] `, &val)
  11. should.Nil(err)
  12. should.Equal([]int{0, 1, 2, 3}, val)
  13. }
  14. func Test_iterator_api_demo(t *testing.T) {
  15. iter := ParseString(ConfigDefault, `[0,1,2,3]`)
  16. total := 0
  17. for iter.ReadArray() {
  18. total += iter.ReadInt()
  19. }
  20. //fmt.Println(total)
  21. }
  22. type People struct {
  23. Name string
  24. Gender string
  25. Age int
  26. Address string
  27. Mobile string
  28. Country string
  29. Height int
  30. }
  31. func jsoniterMarshal(p *People) error {
  32. _, err := Marshal(p)
  33. if nil != err {
  34. return err
  35. }
  36. return nil
  37. }
  38. func stdMarshal(p *People) error {
  39. _, err := json.Marshal(p)
  40. if nil != err {
  41. return err
  42. }
  43. return nil
  44. }
  45. func BenchmarkJosniterMarshal(b *testing.B) {
  46. var p People
  47. p.Address = "上海市徐汇区漕宝路"
  48. p.Age = 30
  49. p.Country = "中国"
  50. p.Gender = "male"
  51. p.Height = 170
  52. p.Mobile = "18502120533"
  53. p.Name = "Elvin"
  54. b.ReportAllocs()
  55. for i := 0; i < b.N; i++ {
  56. err := jsoniterMarshal(&p)
  57. if nil != err {
  58. b.Error(err)
  59. }
  60. }
  61. }
  62. func BenchmarkStdMarshal(b *testing.B) {
  63. var p People
  64. p.Address = "上海市徐汇区漕宝路"
  65. p.Age = 30
  66. p.Country = "中国"
  67. p.Gender = "male"
  68. p.Height = 170
  69. p.Mobile = "18502120533"
  70. p.Name = "Elvin"
  71. b.ReportAllocs()
  72. for i := 0; i < b.N; i++ {
  73. err := stdMarshal(&p)
  74. if nil != err {
  75. b.Error(err)
  76. }
  77. }
  78. }