| 1 |
package benchmark |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"encoding/json" |
| 6 |
"fmt" |
| 7 |
"reflect" |
| 8 |
"testing" |
| 9 |
|
| 10 |
gojson "github.com/goccy/go-json" |
| 11 |
) |
| 12 |
|
| 13 |
// Benchmark decoding from a slow io.Reader that never fills the buffer completely |
| 14 |
func Benchmark_Decode_SlowReader_EncodingJson(b *testing.B) { |
| 15 |
var expected LargePayload |
| 16 |
if err := json.Unmarshal(LargeFixture, &expected); err != nil { |
| 17 |
b.Fatal(err) |
| 18 |
} |
| 19 |
for _, chunkSize := range [5]int{16384, 4096, 1024, 256, 64} { |
| 20 |
b.Run(fmt.Sprintf("chunksize %v", chunkSize), func(b *testing.B) { |
| 21 |
b.ReportAllocs() |
| 22 |
for i := 0; i < b.N; i++ { |
| 23 |
index = 0 |
| 24 |
var got LargePayload |
| 25 |
if err := json.NewDecoder(slowReader{chunkSize: chunkSize}).Decode(&got); err != nil { |
| 26 |
b.Fatal(err) |
| 27 |
} |
| 28 |
if !reflect.DeepEqual(expected, got) { |
| 29 |
b.Fatalf("failed to decode. expected:[%+v] but got:[%+v]", expected, got) |
| 30 |
} |
| 31 |
} |
| 32 |
}) |
| 33 |
} |
| 34 |
} |
| 35 |
|
| 36 |
func Benchmark_Decode_SlowReader_GoJson(b *testing.B) { |
| 37 |
var expected LargePayload |
| 38 |
if err := json.Unmarshal(LargeFixture, &expected); err != nil { |
| 39 |
b.Fatal(err) |
| 40 |
} |
| 41 |
for _, chunkSize := range []int{16384, 4096, 1024, 256, 64} { |
| 42 |
b.Run(fmt.Sprintf("chunksize %v", chunkSize), func(b *testing.B) { |
| 43 |
b.ReportAllocs() |
| 44 |
for i := 0; i < b.N; i++ { |
| 45 |
index = 0 |
| 46 |
var got LargePayload |
| 47 |
if err := gojson.NewDecoder(slowReader{chunkSize: chunkSize}).Decode(&got); err != nil { |
| 48 |
b.Fatal(err) |
| 49 |
} |
| 50 |
if !reflect.DeepEqual(expected, got) { |
| 51 |
b.Fatalf("failed to decode. expected:[%+v] but got:[%+v]", expected, got) |
| 52 |
} |
| 53 |
} |
| 54 |
}) |
| 55 |
} |
| 56 |
} |
| 57 |
|
| 58 |
type slowReader struct { |
| 59 |
chunkSize int |
| 60 |
} |
| 61 |
|
| 62 |
var index int |
| 63 |
|
| 64 |
func (s slowReader) Read(p []byte) (n int, err error) { |
| 65 |
smallBuf := make([]byte, Min(s.chunkSize, len(p))) |
| 66 |
x := bytes.NewReader(LargeFixture) |
| 67 |
n, err = x.ReadAt(smallBuf, int64(index)) |
| 68 |
index += n |
| 69 |
copy(p, smallBuf) |
| 70 |
return |
| 71 |
} |
| 72 |
|
| 73 |
func Min(x, y int) int { |
| 74 |
if x < y { |
| 75 |
return x |
| 76 |
} |
| 77 |
return y |
| 78 |
} |