|
| 1 | +package json |
| 2 | + |
| 3 | +import ( |
| 4 | + "testing" |
| 5 | +) |
| 6 | + |
| 7 | +// Inner implements MarshalJSON to trigger the optimized code path |
| 8 | +type benchInner struct { |
| 9 | + Name string `json:"name"` |
| 10 | + Value int `json:"value"` |
| 11 | +} |
| 12 | + |
| 13 | +func (b benchInner) MarshalJSON() ([]byte, error) { |
| 14 | + return Marshal(struct { |
| 15 | + Name string `json:"name"` |
| 16 | + Value int `json:"value"` |
| 17 | + }{b.Name, b.Value}) |
| 18 | +} |
| 19 | + |
| 20 | +// Nested structure with multiple MarshalJSON calls |
| 21 | +type benchNested struct { |
| 22 | + Inner benchInner `json:"inner"` |
| 23 | + Items []int `json:"items"` |
| 24 | +} |
| 25 | + |
| 26 | +func (b benchNested) MarshalJSON() ([]byte, error) { |
| 27 | + return Marshal(struct { |
| 28 | + Inner benchInner `json:"inner"` |
| 29 | + Items []int `json:"items"` |
| 30 | + }{b.Inner, b.Items}) |
| 31 | +} |
| 32 | + |
| 33 | +// Deeply nested to amplify the effect |
| 34 | +type benchDeep struct { |
| 35 | + Level1 benchNested `json:"level1"` |
| 36 | + Level2 benchNested `json:"level2"` |
| 37 | + Data string `json:"data"` |
| 38 | +} |
| 39 | + |
| 40 | +func (b benchDeep) MarshalJSON() ([]byte, error) { |
| 41 | + return Marshal(struct { |
| 42 | + Level1 benchNested `json:"level1"` |
| 43 | + Level2 benchNested `json:"level2"` |
| 44 | + Data string `json:"data"` |
| 45 | + }{b.Level1, b.Level2, b.Data}) |
| 46 | +} |
| 47 | + |
| 48 | +func BenchmarkMarshalNestedMarshalJSON(b *testing.B) { |
| 49 | + data := benchDeep{ |
| 50 | + Level1: benchNested{ |
| 51 | + Inner: benchInner{Name: "test1", Value: 100}, |
| 52 | + Items: []int{1, 2, 3, 4, 5}, |
| 53 | + }, |
| 54 | + Level2: benchNested{ |
| 55 | + Inner: benchInner{Name: "test2", Value: 200}, |
| 56 | + Items: []int{6, 7, 8, 9, 10}, |
| 57 | + }, |
| 58 | + Data: "some test data here", |
| 59 | + } |
| 60 | + |
| 61 | + b.ResetTimer() |
| 62 | + for i := 0; i < b.N; i++ { |
| 63 | + _, err := Marshal(data) |
| 64 | + if err != nil { |
| 65 | + b.Fatal(err) |
| 66 | + } |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +// Slice of nested structs - common real-world pattern |
| 71 | +func BenchmarkMarshalSliceOfNestedMarshalJSON(b *testing.B) { |
| 72 | + data := make([]benchDeep, 50) |
| 73 | + for i := range data { |
| 74 | + data[i] = benchDeep{ |
| 75 | + Level1: benchNested{ |
| 76 | + Inner: benchInner{Name: "test1", Value: i}, |
| 77 | + Items: []int{1, 2, 3, 4, 5}, |
| 78 | + }, |
| 79 | + Level2: benchNested{ |
| 80 | + Inner: benchInner{Name: "test2", Value: i * 2}, |
| 81 | + Items: []int{6, 7, 8, 9, 10}, |
| 82 | + }, |
| 83 | + Data: "some test data here that is a bit longer to simulate real payloads", |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + b.ResetTimer() |
| 88 | + for i := 0; i < b.N; i++ { |
| 89 | + _, err := Marshal(data) |
| 90 | + if err != nil { |
| 91 | + b.Fatal(err) |
| 92 | + } |
| 93 | + } |
| 94 | +} |
0 commit comments