Home > Java > body text

Protobuf partial serialization of common fields in Java

WBOY
Release: 2024-02-12 15:45:06
forward
1189 people have browsed it

Question content

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 (?).

Solution

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);
Copy after login

(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);
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template