internal/impl: add MessageState to every generated message
We define MessageState, which is essentially an atomically set *MessageInfo.
By nesting this as the first field in every generated message, we can
implement the reflective methods on a *MessageState when obtained by
unsafe casting a concrete message pointer as a *MessageState.
The MessageInfo held by MessageState provides additional Go type information
to interpret the memory that comes after the contents of the MessageState.
Since we are nesting a MessageState in every message,
the memory use of every message instance grows by 8B.
On average, the body of ProtoReflect grows from 133B to 202B (+50%).
However, this is offset by XXX_Methods, which is 108B and
will be removed in a future CL. Taking into account the eventual removal
of XXX_Methods, this is a net reduction of 25%.
name old time/op new time/op delta
Name/Value-4 70.3ns ± 2% 17.5ns ± 6% -75.08% (p=0.000 n=10+10)
Name/Nil-4 70.6ns ± 3% 33.4ns ± 2% -52.66% (p=0.000 n=10+10)
name old alloc/op new alloc/op delta
Name/Value-4 16.0B ± 0% 0.0B -100.00% (p=0.000 n=10+10)
Name/Nil-4 16.0B ± 0% 0.0B -100.00% (p=0.000 n=10+10)
name old allocs/op new allocs/op delta
Name/Value-4 1.00 ± 0% 0.00 -100.00% (p=0.000 n=10+10)
Name/Nil-4 1.00 ± 0% 0.00 -100.00% (p=0.000 n=10+10)
Change-Id: I92bd58dc681c57c92612fd5ba7fc066aea34e95a
Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/185460
Reviewed-by: Damien Neil <dneil@google.com>
diff --git a/internal/testprotos/legacy/legacy.pb.go b/internal/testprotos/legacy/legacy.pb.go
index 717cd58..ff29662 100644
--- a/internal/testprotos/legacy/legacy.pb.go
+++ b/internal/testprotos/legacy/legacy.pb.go
@@ -30,6 +30,7 @@
)
type Legacy struct {
+ state protoimpl.MessageState
F1 *proto2_v0_0.Message `protobuf:"bytes,1,opt,name=f1,proto3" json:"f1,omitempty"`
F2 *proto3_v0_0.Message `protobuf:"bytes,2,opt,name=f2,proto3" json:"f2,omitempty"`
F3 *proto2_v0_01.Message `protobuf:"bytes,3,opt,name=f3,proto3" json:"f3,omitempty"`
@@ -57,10 +58,18 @@
func (*Legacy) ProtoMessage() {}
func (x *Legacy) ProtoReflect() protoreflect.Message {
- return file_legacy_legacy_proto_msgTypes[0].MessageOf(x)
+ mi := &file_legacy_legacy_proto_msgTypes[0]
+ if protoimpl.UnsafeEnabled && x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
}
-func (m *Legacy) XXX_Methods() *protoiface.Methods {
+func (x *Legacy) XXX_Methods() *protoiface.Methods {
return file_legacy_legacy_proto_msgTypes[0].Methods()
}
@@ -305,9 +314,11 @@
if !protoimpl.UnsafeEnabled {
file_legacy_legacy_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*Legacy); i {
- case 12:
- return &v.sizeCache
+ case 0:
+ return &v.state
case 13:
+ return &v.sizeCache
+ case 14:
return &v.unknownFields
default:
return nil