Skip to content

Commit

Permalink
Optimize string unmarshaling
Browse files Browse the repository at this point in the history
  • Loading branch information
outofforest committed Sep 1, 2024
1 parent 905e939 commit cc8168b
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 4 deletions.
19 changes: 19 additions & 0 deletions test/benchmark_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,21 @@ func BenchmarkMarshalingByteSlices(b *testing.B) {
b.StopTimer()
}

func BenchmarkMarshalingStrings(b *testing.B) {
b.StopTimer()
b.ResetTimer()

var msg2 pkg1.MsgString
buf := make([]byte, msgStrings.Size())

b.StartTimer()
for range b.N {
msgStrings.Marshal(buf)
msg2.Unmarshal(buf)
}
b.StopTimer()
}

var (
msgMixed = pkg1.MsgMixed{
Value1: map[string]spkg1.SubMsg{
Expand Down Expand Up @@ -345,6 +360,10 @@ var (
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
},
}
msgStrings = pkg1.MsgString{
//nolint:lll
Value: "fdfsdfdsgfdlghfdkghkdfhkdfhkjghdfkhgkjdfhgkjdfhkjdgfhkjhdfkjhgkjdfhkjdfhkjdfhkjhfdkjhkjdfhkjdfhkjfdghkjhfdkjhgkjdfhkjdfhkjghfdkjhgdfkjhkjfdhkjfhkjghdfkjhdfkhgkjsfysdfydgdfkghdfkjghkfd",
}
)

var _ iface = implValue{}
Expand Down
18 changes: 14 additions & 4 deletions types/tstring/builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ func (b Builder) MarshalCodeTemplate(_ *uint64) string {

// UnmarshalCodeTemplate returns code template unmarshaling the data.
func (b Builder) UnmarshalCodeTemplate(_ *uint64) string {
unsafe := b.tm.Import("unsafe")
code := `{
var l uint64
`
Expand All @@ -79,10 +80,19 @@ func (b Builder) UnmarshalCodeTemplate(_ *uint64) string {
helpers.Execute(buf, types.UInt64Unmarshal("uint64"), "l")
code += types.AddIndent(buf.String(), 1) + "\n"

t := b.tm.TypeName(b.msgType, b.fieldType)
code += fmt.Sprintf(` {{ . }} = %[1]s(b[o : o+l])
o += l
}`, t)
code += ` if l > 0 {
`
if b.fieldType.Name() == "string" {
code += fmt.Sprintf(" {{ . }} = %[1]s.String((*byte)(%[1]s.Pointer(&b[o])), l)\n", unsafe)
} else {
code += fmt.Sprintf(" {{ . }} = %[2]s(%[1]s.String((*byte)(%[1]s.Pointer(&b[o])), l))\n", unsafe,
b.tm.TypeName(b.msgType, b.fieldType))
}
code += ` o += l
} else {
{{ . }} = ""
}
}`

return code
}

0 comments on commit cc8168b

Please sign in to comment.