| 1 |
package benchmark |
| 2 |
|
| 3 |
import ( |
| 4 |
"testing" |
| 5 |
|
| 6 |
gojson "github.com/goccy/go-json" |
| 7 |
) |
| 8 |
|
| 9 |
// The values of interface types which are set before the decoding: a value of interface{} which holds a pointer |
| 10 |
// is decoded into what it points to, and a value of an interface type with methods is decoded by its |
| 11 |
// unmarshaler. |
| 12 |
|
| 13 |
type ifaceItem struct { |
| 14 |
ID int `json:"id"` |
| 15 |
Name string `json:"name"` |
| 16 |
} |
| 17 |
|
| 18 |
type ifacePointerPayload struct { |
| 19 |
A, B, C, D, E, F, G, H any |
| 20 |
} |
| 21 |
|
| 22 |
func newIfacePointerPayload() *ifacePointerPayload { |
| 23 |
return &ifacePointerPayload{ |
| 24 |
A: &ifaceItem{}, B: &ifaceItem{}, C: &ifaceItem{}, D: &ifaceItem{}, |
| 25 |
E: &ifaceItem{}, F: &ifaceItem{}, G: &ifaceItem{}, H: &ifaceItem{}, |
| 26 |
} |
| 27 |
} |
| 28 |
|
| 29 |
// ifaceUnmarshaler is an interface type with methods, whose values are decoded by their unmarshaler. |
| 30 |
type ifaceUnmarshaler interface { |
| 31 |
UnmarshalJSON([]byte) error |
| 32 |
} |
| 33 |
|
| 34 |
// ifaceCount is decoded into the length of its value. |
| 35 |
type ifaceCount int |
| 36 |
|
| 37 |
func (c *ifaceCount) UnmarshalJSON(b []byte) error { |
| 38 |
*c = ifaceCount(len(b)) |
| 39 |
return nil |
| 40 |
} |
| 41 |
|
| 42 |
type ifaceUnmarshalerPayload struct { |
| 43 |
A, B, C, D, E, F, G, H ifaceUnmarshaler |
| 44 |
} |
| 45 |
|
| 46 |
func newIfaceUnmarshalerPayload() *ifaceUnmarshalerPayload { |
| 47 |
return &ifaceUnmarshalerPayload{ |
| 48 |
A: new(ifaceCount), B: new(ifaceCount), C: new(ifaceCount), D: new(ifaceCount), |
| 49 |
E: new(ifaceCount), F: new(ifaceCount), G: new(ifaceCount), H: new(ifaceCount), |
| 50 |
} |
| 51 |
} |
| 52 |
|
| 53 |
func ifaceDocument(value string) []byte { |
| 54 |
b := []byte{'{'} |
| 55 |
for i, name := range []string{"A", "B", "C", "D", "E", "F", "G", "H"} { |
| 56 |
if i > 0 { |
| 57 |
b = append(b, ',') |
| 58 |
} |
| 59 |
b = append(b, `"`+name+`":`+value...) |
| 60 |
} |
| 61 |
return append(b, '}') |
| 62 |
} |
| 63 |
|
| 64 |
func Benchmark_Decode_InterfacePointer_Unmarshal_GoJson(b *testing.B) { |
| 65 |
data := ifaceDocument(`{"id":1,"name":"item"}`) |
| 66 |
v := newIfacePointerPayload() |
| 67 |
b.SetBytes(int64(len(data))) |
| 68 |
b.ReportAllocs() |
| 69 |
b.ResetTimer() |
| 70 |
for i := 0; i < b.N; i++ { |
| 71 |
if err := gojson.Unmarshal(data, v); err != nil { |
| 72 |
b.Fatal(err) |
| 73 |
} |
| 74 |
} |
| 75 |
} |
| 76 |
|
| 77 |
func Benchmark_Decode_InterfaceUnmarshaler_Unmarshal_GoJson(b *testing.B) { |
| 78 |
data := ifaceDocument(`[1,2,3]`) |
| 79 |
v := newIfaceUnmarshalerPayload() |
| 80 |
b.SetBytes(int64(len(data))) |
| 81 |
b.ReportAllocs() |
| 82 |
b.ResetTimer() |
| 83 |
for i := 0; i < b.N; i++ { |
| 84 |
if err := gojson.Unmarshal(data, v); err != nil { |
| 85 |
b.Fatal(err) |
| 86 |
} |
| 87 |
} |
| 88 |
} |