SerializeToArray return value C++

1,706 views
Skip to first unread message

bentr...@gmail.com

unread,
Aug 11, 2016, 12:52:38 AM8/11/16
to Protocol Buffers
In the C++ MessageLite class, SerializeToArray calls ByteSize (Protobuf implementation) to determine what size is required to write to buffer. It then writes to the buffer using this size but only returns true if it was successful. Maybe it would be a better idea to return the size written to buffer (using 0 if unsuccessful). Under the current implementation we must call ByteSize twice, which is an expensive operation. Once to write to buffer and a second time on the client side to determine the size for sending.

If anyone has any reasoning behind the current design or alternative solutions please let me know. Or if this has been raised before feel free to leave a link. It would be great to hear your thoughts!

Adam Cozzette

unread,
Aug 12, 2016, 11:27:49 AM8/12/16
to bentr...@gmail.com, Protocol Buffers
I think there are a couple different ways to avoid calling ByteSize() more than once:
1. You can call ByteSize() yourself and save the result, and then call SerializeWithCachedSizesToArray(). The serialization will use the cached size and thus will not recompute it.
2. You can call SerializeToArray() and then (assuming it was successful) call GetCachedSize() afterward to find out how many bytes were written.

Would one of those help for your use case? It seems to me like you would probably want to go with option 1 since in practice you probably need to know how large the message is so that you can ensure your buffer is large enough before you attempt the serialization.

On Wed, Aug 10, 2016 at 6:46 PM, <bentr...@gmail.com> wrote:
In the C++ MessageLite class, SerializeToArray calls ByteSize (Protobuf implementation) to determine what size is required to write to buffer. It then writes to the buffer using this size but only returns true if it was successful. Maybe it would be a better idea to return the size written to buffer (using 0 if unsuccessful). Under the current implementation we must call ByteSize twice, which is an expensive operation. Once to write to buffer and a second time on the client side to determine the size for sending.

If anyone has any reasoning behind the current design or alternative solutions please let me know. Or if this has been raised before feel free to leave a link. It would be great to hear your thoughts!

--
You received this message because you are subscribed to the Google Groups "Protocol Buffers" group.
To unsubscribe from this group and stop receiving emails from it, send an email to protobuf+unsubscribe@googlegroups.com.
To post to this group, send email to prot...@googlegroups.com.
Visit this group at https://groups.google.com/group/protobuf.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages