I have a protobuf message that needs to be sent to multiple clients. The message has the same data for each client, except for one field (sequence number) that is different for each client. Now I can change the fields in the generated Java message object and serialize the message separately for each client. But is there a way to serialize everything but one field and then just serialize that field for each client (e.g. swap the corresponding bytes in the serialized message or something)?
Edit: I've seen the mergeFrom method to merge two messages, but from my understanding it parses the message first, then swaps the data, and then you can serialize it again, so it's not a performance optimization at all (?).
First of all, I want to be very sure that this is actually performance related. If the protocol buffer messages are not large (I wouldn't even consider this if they weren't multiple kilobytes), then I would expect this to have essentially zero impact on performance, and you shouldn't even try to optimize it.
Assuming you've identified this as a bottleneck, this isn't difficult. The concatenated serialization prototype constructs the merged form, so presumably this is
myMessage.toBuilder().clearSpecialField().build().writeTo(outputStream); MyMessage.newBuilder().setSpecialField(...).build().writeTo(outputStream);
(If you have made special_field
a required field (against best practices), you may want to use buildPartial
instead.)
Then you read it as a raw message
MyMessage.parseFrom(inputStream);
The above is the detailed content of Protobuf partial serialization of common fields in Java. For more information, please follow other related articles on the PHP Chinese website!