Skip to content

Commit

Permalink
Merge pull request #4 from itchyny/reduce-allocation
Browse files Browse the repository at this point in the history
Reduce allocations by avoiding strings.Split
  • Loading branch information
Songmu committed Sep 3, 2020
2 parents c30af2b + e268038 commit a608c3f
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 11 deletions.
26 changes: 18 additions & 8 deletions decode.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,14 +44,23 @@ type ltsvMap map[string]string

func data2map(data []byte) (ltsvMap, error) {
d := string(data)
fields := strings.Split(d, "\t")
l := ltsvMap{}
for _, v := range fields {
kv := strings.SplitN(strings.TrimSpace(v), ":", 2)
if len(kv) != 2 {
var i int
var v string
for i < len(d) {
j := strings.IndexByte(d[i:], '\t')
if j >= 0 {
v = d[i : i+j]
i += j + 1
} else {
v = d[i:]
i = len(d)
}
k := strings.IndexByte(v, ':')
if k < 0 {
return nil, fmt.Errorf("not a ltsv: %s", d)
}
l[strings.TrimSpace(kv[0])] = strings.TrimSpace(kv[1])
l[strings.TrimSpace(v[:k])] = strings.TrimSpace(v[k+1:])
}
return l, nil
}
Expand Down Expand Up @@ -93,9 +102,10 @@ func Unmarshal(data []byte, v interface{}) error {
ft := t.Field(i)
fv := rv.Field(i)

tag := ft.Tag.Get("ltsv")
tags := strings.Split(tag, ",")
key := tags[0]
key := ft.Tag.Get("ltsv")
if i := strings.IndexByte(key, ','); i >= 0 {
key = key[:i]
}
if key == "-" {
continue
}
Expand Down
12 changes: 12 additions & 0 deletions decode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,3 +96,15 @@ func TestUnmarshal(t *testing.T) {
}
}
}

func BenchmarkUnmarshalStruct(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tt := range decodeTests {
s := &ss{}
err := Unmarshal([]byte(tt.Input), s)
if err != nil {
b.Error(err)
}
}
}
}
7 changes: 4 additions & 3 deletions encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,10 @@ func makeStructWriter(v reflect.Value) fieldWriter {
writers := make([]fieldWriter, n)
for i := 0; i < n; i++ {
ft := t.Field(i)
tag := ft.Tag.Get("ltsv")
tags := strings.Split(tag, ",")
key := tags[0]
key := ft.Tag.Get("ltsv")
if i := strings.IndexByte(key, ','); i >= 0 {
key = key[:i]
}
if key == "-" {
continue
}
Expand Down

0 comments on commit a608c3f

Please sign in to comment.