Skip to content

features/pool: reuse map type fields #156

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
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
1 change: 1 addition & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ gen-testproto: get-grpc-testproto gen-wkt-testproto install
testproto/empty/empty.proto \
testproto/pool/pool.proto \
testproto/pool/pool_with_slice_reuse.proto \
testproto/pool/pool_with_map_reuse.proto \
testproto/pool/pool_with_oneof.proto \
testproto/proto3opt/opt.proto \
testproto/proto2/scalars.proto \
Expand Down
15 changes: 15 additions & 0 deletions features/pool/pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,21 @@ func (p *pool) message(message *protogen.Message) {
}
p.P(fmt.Sprintf("f%d", len(saved)), ` := m.`, fieldName, `[:0]`)
saved = append(saved, field)
} else if field.Desc.IsMap() {
switch field.Desc.MapValue().Kind() {
case protoreflect.MessageKind, protoreflect.GroupKind:
valueField := field.Message.Fields[1]
p.P(`for _, v := range m.`, fieldName, `{`)
if p.ShouldPool(valueField.Message) {
p.P(`v.ResetVT()`)
} else {
p.P(`v.Reset()`)
}
p.P(`}`)
}
p.P(`clear(m.`, fieldName, `)`)
p.P(fmt.Sprintf("f%d", len(saved)), ` := m.`, fieldName)
saved = append(saved, field)
} else if field.Oneof != nil && !field.Oneof.Desc.IsSynthetic() {
if p.ShouldPool(field.Message) {
p.P(`if oneof, ok := m.`, field.Oneof.GoName, `.(*`, field.GoIdent, `); ok {`)
Expand Down
19 changes: 19 additions & 0 deletions testproto/pool/pool_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -186,3 +186,22 @@ func Test_Pool_Optional(t *testing.T) {
mFromPool := MemoryPoolExtensionFromVTPool()
require.True(t, mFromPool.EqualVT(&MemoryPoolExtension{}))
}

func Test_Pool_Reuse_Map(t *testing.T) {
allocs := testing.AllocsPerRun(10, func() {
obj := MapReuseTest1FromVTPool()
if obj.GetIntToStringMap() == nil {
obj.IntToStringMap = make(map[int32]string)
}
obj.IntToStringMap[1] = "test1"
obj.IntToStringMap[2] = "test2"
obj.IntToStringMap[3] = "test3"
if obj.GetStringToEnumMap() == nil {
obj.StringToEnumMap = make(map[string]MapReuseTest1_TEST)
}
obj.StringToEnumMap["test1"] = MapReuseTest1_test1
obj.StringToEnumMap["test2"] = MapReuseTest1_test2
obj.ReturnToVTPool()
})
require.Less(t, int(allocs), 1)
}
Loading