Skip to content

Commit

Permalink
Added Benchmark for SliceEncoder - String
Browse files Browse the repository at this point in the history
Added SliceEncoder Unit test
  • Loading branch information
John Gillott committed Jan 16, 2020
1 parent 03c584d commit f4a540a
Show file tree
Hide file tree
Showing 2 changed files with 97 additions and 3 deletions.
86 changes: 86 additions & 0 deletions jingo_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package jingo

import (
"bytes"
"encoding/json"
"fmt"
"strconv"
Expand Down Expand Up @@ -191,6 +192,91 @@ func BenchmarkUnicodeStdLib(b *testing.B) {
}
}

func TestSliceEncoder(t *testing.T) {

enc := NewSliceEncoder([]string{})

type marshaler interface {
Marshal(s interface{}, w *Buffer)
}

tests := []struct {
name string
enc marshaler
v interface{}
want []byte
}{
{
"SliceEncoder String - Empty",
enc,
&[]string{},
[]byte("[]"),
},
{
"SliceEncoder String - Single",
enc,
&[]string{"0"},
[]byte(`["0"]`),
},
{
"SliceEncoder String - Many",
enc,
&[]string{"0", "1", "2"},
[]byte(`["0","1","2"]`),
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {

buf := NewBufferFromPool()
defer buf.ReturnToPool()

tt.enc.Marshal(tt.v, buf)

if !bytes.Equal(tt.want, buf.Bytes) {
t.Errorf("\nwant:\n%s\ngot:\n%s", tt.want, buf.Bytes)
}

})
}
}

func BenchmarkSlice(b *testing.B) {

ss := []string{
"a name",
"another name",
"another",
"and one more",
"last one, promise",
}

var enc = NewSliceEncoder([]string{})

b.StartTimer()
for i := 0; i < b.N; i++ {
buf := NewBufferFromPool()
enc.Marshal(&ss, buf)
buf.ReturnToPool()
}
}

func BenchmarkSliceStdLib(b *testing.B) {
ss := []string{
"a name",
"another name",
"another",
"and one more",
"last one, promise",
}

b.StartTimer()
for i := 0; i < b.N; i++ {
json.Marshal(&ss)
}
}

// var fakeType = SmallPayload{}
// var fake = NewSmallPayload()

Expand Down
14 changes: 11 additions & 3 deletions sliceencoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,12 +115,20 @@ func (e *SliceEncoder) stringInstr() {

sl := *(*reflect.SliceHeader)(v)
for i := uintptr(0); i < uintptr(sl.Len); i++ {

if i == 0 {
w.WriteByte('"')
}

if i > zero {
w.WriteByte(',')
w.Write([]byte(`","`))
}
w.WriteByte('"')

ptrStringToBuf(unsafe.Pointer(sl.Data+(i*e.offset)), w)
w.WriteByte('"')

if i == uintptr(sl.Len)-1 {
w.WriteByte('"')
}
}

w.WriteByte(']')
Expand Down

0 comments on commit f4a540a

Please sign in to comment.