Skip to content

Commit 743ad54

Browse files
feat: speed up ProtoMethods
The ProtoMethods is called for every unmarshal, which in turn allocates an protoiface.Methods. The Methods object does not refer to a partucular message object, so the allocation can be saved by one-time initialization at startup. Found by the the alecthomas/go_serialization_benchmarks suite: go test -bench='Pulsar' -memprofile mem.out -cpu 6 ./ Before: goos: darwin goarch: arm64 pkg: github.com/alecthomas/go_serialization_benchmarks Benchmark_Pulsar_Marshal-6 7480744 154.1 ns/op 51.57 B/serial 96 B/op 2 allocs/op Benchmark_Pulsar_Unmarshal-6 5057922 236.9 ns/op 51.60 B/serial 256 B/op 7 allocs/op After: Benchmark_Pulsar_Marshal-6 7251019 153.9 ns/op 51.57 B/serial 96 B/op 2 allocs/op Benchmark_Pulsar_Unmarshal-6 6409070 187.2 ns/op 51.63 B/serial 160 B/op 5 allocs/op
1 parent 760914f commit 743ad54

File tree

1 file changed

+9
-2
lines changed

1 file changed

+9
-2
lines changed

features/fastreflection/proto_message.go

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -288,19 +288,26 @@ func (g *fastGenerator) genIsValid() {
288288
}
289289

290290
func (g *fastGenerator) genProtoMethods() {
291+
varName := g.typeName + "ProtoMethods"
292+
291293
g.P("// ProtoMethods returns optional fastReflectionFeature-path implementations of various operations.")
292294
g.P("// This method may return nil.")
293295
g.P("//")
294296
g.P("// The returned methods type is identical to")
295297
g.P(`// "google.golang.org/protobuf/runtime/protoiface".Methods.`)
296298
g.P("// Consult the protoiface package documentation for details.")
297-
g.P("func (x *", g.typeName, ") ProtoMethods() *", protoifacePkg.Ident("Methods"), " {")
299+
g.P("func (*", g.typeName, ") ProtoMethods() *", protoifacePkg.Ident("Methods"), " {")
300+
g.P("return ", varName)
301+
g.P("}")
302+
303+
g.P("var ", varName, " *", protoifacePkg.Ident("Methods"))
298304

305+
g.P("func init() {")
299306
g.genSizeMethod()
300307
g.genMarshalMethod()
301308
g.genUnmarshalMethod()
302309

303-
g.P("return &", protoifacePkg.Ident("Methods"), "{ ")
310+
g.P(varName, " = &", protoifacePkg.Ident("Methods"), "{ ")
304311
g.P("NoUnkeyedLiterals: struct{}{},")
305312
g.P("Flags: ", protoifacePkg.Ident("SupportMarshalDeterministic"), "|", protoifacePkg.Ident("SupportUnmarshalDiscardUnknown"), ",")
306313
g.P("Size: size,")

0 commit comments

Comments
 (0)