0

When using the Go implementation of GRPC, what is considered best practice in regards to reusing or sharing empty or unchanging responses between multiple requests? This saves an unnecessary allocation - but is there any reason not to?

For example:

var emptyPingResponse = &pb.PingResponse{}
var staticBuildInfo  = &pb.GetBuildInfoResponse {
  Version:    /* ... */,
  BuildDate:  /* ... */,
}

func (*Service) Ping(ctx context.Context, req *pb.PingRequest) (res *pb.PingResponse, err error) {
  // do something here
  return emptyPingResponse, nil
}

func (*Service) GetBuildInfo(ctx context.Context, req *pb.GetBuildInfoRequest) (res *pb.GetBuildInfoResponse, err error) {
  return staticBuildInfo, nil
}
Phillip Elm
  • 2,094
  • 2
  • 16
  • 27
  • 2
    The Go struct will just be serialized to the protobuf wire format. Reusing the same instance won't be a problem, as long as you are sure the struct is de-facto immutable. Anyway, the alloc you save is not going to be the bottleneck of your program – blackgreen Sep 28 '21 at 19:43
  • This is a micro-optimization with negligible effect, which is by the way not necessarily positive. Allocating a struct for the duration of a function can be faster than allocating it for a longer time because locally-scoped allocations are easier to garbage-collect. – rustyx Sep 29 '21 at 18:49
  • @rustyx yeah that's my thinking here. I can see there being useful cases where immutable data requires some calculation first - but overall this does seem undesirable. – Phillip Elm Sep 29 '21 at 21:50
  • 1
    @db80 in my experience, some teams (and tools) require that each request and response has its own unique message, as what is currently an empty message might have fields added later. – Phillip Elm Sep 30 '21 at 18:41
  • This thing won't to be a bottleneck in your app. I'm going to quote the zen of python: "Readability counts. Special cases aren't special enough to break the rules." – kucherenkovova Dec 01 '21 at 12:57
  • @kucherenkovova - yep. I think I was more interested in knowing the internals - ie, are messages reusable. – Phillip Elm Dec 02 '21 at 07:37

0 Answers0