【发布时间】:2018-04-20 08:09:45
【问题描述】:
我有一个这样的消息定义:
message Command{
oneof type{
Point point = 1;
Rotate rotate = 2;
Move move = 3;
... //about 100 messages
}
}
然后protoc生成SerializeWithCachedSizes函数:
void Command::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:coopshare.proto.Command)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
// .coopshare.proto.Point point = 1;
if (has_point()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, *type_.point_, output);
}
// .coopshare.proto.Rotate rotate = 2;
if (has_rotate()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
2, *type_.rotate_, output);
}
// .coopshare.proto.Move move = 3;
if (has_move()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
3, *type_.move_, output);
}
“oneof”消息将特定类型保存在_oneof_case_中。我认为使用 switch-case 更有效。
但是为什么 protobuf 还是会生成这样的代码呢?
【问题讨论】:
-
编译器很聪明,所以做任何一个都可能无关紧要。编译器能够将一长串
if/else块转换为查找表。如果您尝试使用一个小的switch块来编写程序,您会看到编译器会将其转换为几个条件跳转。生成工具可能会这样做,因为它更容易生成。
标签: protocol-buffers