Home > Net >  How to get the actual size of a protocol buffer message before serialization?
How to get the actual size of a protocol buffer message before serialization?

Time:06-15

I defined a message in *.proto file and set the values using reflection. I need to find out how many bytes are parsed per second with SerializeToString() API. Is it possible to get the actual size of the message before calling SerializeToString?

CodePudding user response:

It depends on which size you're interested in.

If you want to know how large the serialized protobuf message returned by MessageLite::SerializeToString() is going to be you can use Message::ByteSizeLong().

Example:

ExampleMessage msg;
msg.set_example(12);

std::size_t expectedSize = msg.ByteSizeLong();

std::string result;
msg.SerializeToString(&result);

assert(expectedSize == result.size());

This is also the way SerializeToString() calculates the size of the message internally to resize the std::string to have enough space for the entire message.


On the other hand if you want to know how much memory the message currently requires in unserialized form you can use Message::SpaceUsedLong() - which will give you an estimate of that size.

Example:

ExampleMessage msg;
msg.set_example(12);

std::size_t approximateInMemorySize = msg.SpaceUsedLong();
  • Related