Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions internal/apijson/array_bench_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package apijson

import (
"encoding/json"
"fmt"
"strings"
"testing"
)

func makeIPSlice(n int) []string {
out := make([]string, n)
for i := 0; i < n; i++ {
out[i] = fmt.Sprintf("10.%d.%d.%d", (i>>16)&0xff, (i>>8)&0xff, i&0xff)
}
return out
}

func TestArrayMarshalCorrectness(t *testing.T) {
for _, n := range []int{0, 1, 2, 100} {
in := makeIPSlice(n)
got, err := Marshal(in)
if err != nil {
t.Fatalf("Marshal(n=%d) error: %v", n, err)
}
want, _ := json.Marshal(in)
if !strings.EqualFold(string(got), string(want)) {
t.Fatalf("n=%d: got=%s want=%s", n, got, want)
}
}
}

func benchmarkArrayMarshal(b *testing.B, n int) {
in := makeIPSlice(n)
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_, err := Marshal(in)
if err != nil {
b.Fatal(err)
}
}
}

func BenchmarkArrayMarshal_100(b *testing.B) { benchmarkArrayMarshal(b, 100) }
func BenchmarkArrayMarshal_1000(b *testing.B) { benchmarkArrayMarshal(b, 1000) }
func BenchmarkArrayMarshal_5000(b *testing.B) { benchmarkArrayMarshal(b, 5000) }
func BenchmarkArrayMarshal_10000(b *testing.B) { benchmarkArrayMarshal(b, 10000) }
func BenchmarkArrayMarshal_30000(b *testing.B) { benchmarkArrayMarshal(b, 30000) }
26 changes: 15 additions & 11 deletions internal/apijson/encoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -183,25 +183,29 @@ func (e *encoder) newArrayTypeEncoder(t reflect.Type) encoderFunc {
itemEncoder := e.typeEncoder(t.Elem())

return func(value reflect.Value) ([]byte, error) {
json := []byte("[]")
for i := 0; i < value.Len(); i++ {
var value, err = itemEncoder(value.Index(i))
n := value.Len()
if n == 0 {
return []byte("[]"), nil
}
var buf bytes.Buffer
buf.WriteByte('[')
for i := 0; i < n; i++ {
item, err := itemEncoder(value.Index(i))
if err != nil {
return nil, err
}
if value == nil {
if item == nil {
// Assume that empty items should be inserted as `null` so that the output array
// will be the same length as the input array
value = []byte("null")
item = []byte("null")
}

json, err = sjson.SetRawBytes(json, "-1", value)
if err != nil {
return nil, err
if i > 0 {
buf.WriteByte(',')
}
buf.Write(item)
}

return json, nil
buf.WriteByte(']')
return buf.Bytes(), nil
}
}

Expand Down