jsoniter_reflect_test.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package jsoniter
  2. import (
  3. "testing"
  4. "fmt"
  5. "encoding/json"
  6. )
  7. func Test_reflect_str(t *testing.T) {
  8. iter := ParseString(`"hello"`)
  9. str := ""
  10. iter.Read(&str)
  11. if str != "hello" {
  12. t.Fatal(str)
  13. }
  14. }
  15. type StructOfString struct {
  16. field1 string
  17. field2 string
  18. }
  19. func Test_reflect_struct(t *testing.T) {
  20. iter := ParseString(`{"field1": "hello", "field2": "world"}`)
  21. struct_ := StructOfString{}
  22. iter.Read(&struct_)
  23. if struct_.field1 != "hello" {
  24. fmt.Println(iter.Error)
  25. t.Fatal(struct_.field1)
  26. }
  27. if struct_.field2 != "world" {
  28. fmt.Println(iter.Error)
  29. t.Fatal(struct_.field1)
  30. }
  31. }
  32. func Benchmark_jsoniter_reflect(b *testing.B) {
  33. b.ReportAllocs()
  34. for n := 0; n < b.N; n++ {
  35. iter := ParseString(`{"field1": "hello", "field2": "world"}`)
  36. struct_ := StructOfString{}
  37. iter.Read(&struct_)
  38. }
  39. }
  40. func Benchmark_jsoniter_direct(b *testing.B) {
  41. b.ReportAllocs()
  42. for n := 0; n < b.N; n++ {
  43. iter := ParseString(`{"field1": "hello", "field2": "world"}`)
  44. struct_ := StructOfString{}
  45. for field := iter.ReadObject(); field != ""; field = iter.ReadObject() {
  46. switch field {
  47. case "field1":
  48. struct_.field1 = iter.ReadString()
  49. case "field2":
  50. struct_.field2 = iter.ReadString()
  51. default:
  52. iter.Skip()
  53. }
  54. }
  55. }
  56. }
  57. func Benchmark_json_reflect(b *testing.B) {
  58. b.ReportAllocs()
  59. for n := 0; n < b.N; n++ {
  60. struct_ := StructOfString{}
  61. json.Unmarshal([]byte(`{"field1": "hello", "field2": "world"}`), &struct_)
  62. }
  63. }