jsoniter_demo_test.go 1.4 KB

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