From e47b45ad9f7a5f63d6508ed504fcc2cabcfc9087 Mon Sep 17 00:00:00 2001 From: ningmingxiao Date: Mon, 16 Mar 2026 20:04:01 +0800 Subject: [PATCH] perf: optimize bytes field conversion by eliminating string copy Signed-off-by: ningmingxiao --- internal/impl/message_opaque_gen.go | 6 ++++-- internal/impl/message_reflect_field_gen.go | 4 +++- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/internal/impl/message_opaque_gen.go b/internal/impl/message_opaque_gen.go index a69825699..90d206723 100644 --- a/internal/impl/message_opaque_gen.go +++ b/internal/impl/message_opaque_gen.go @@ -8,6 +8,7 @@ package impl import ( "reflect" + "unsafe" "google.golang.org/protobuf/reflect/protoreflect" ) @@ -94,10 +95,11 @@ func getterForOpaqueNullableScalar(mi *MessageInfo, index uint32, fd protoreflec if *x == nil { return conv.Zero() } - if len(**x) == 0 { + s := **x + if len(s) == 0 { return protoreflect.ValueOfBytes(nil) } - return protoreflect.ValueOfBytes([]byte(**x)) + return protoreflect.ValueOfBytes(unsafe.Slice(unsafe.StringData(s), len(s))) } } return func(p pointer) protoreflect.Value { diff --git a/internal/impl/message_reflect_field_gen.go b/internal/impl/message_reflect_field_gen.go index af5e063a1..f587b2640 100644 --- a/internal/impl/message_reflect_field_gen.go +++ b/internal/impl/message_reflect_field_gen.go @@ -8,6 +8,7 @@ package impl import ( "reflect" + "unsafe" "google.golang.org/protobuf/reflect/protoreflect" ) @@ -122,7 +123,8 @@ func getterForNullableScalar(fd protoreflect.FieldDescriptor, fs reflect.StructF if len(**x) == 0 { return protoreflect.ValueOfBytes(nil) } - return protoreflect.ValueOfBytes([]byte(**x)) + s := **x + return protoreflect.ValueOfBytes(unsafe.Slice(unsafe.StringData(s), len(s))) } } return func(p pointer) protoreflect.Value {