1

现在我有一个应用程序,我的 iPhone 应用程序发送一个请求,该请求在 .NET/C# 中处理,序列化为 XML,并在 Objective-c 中的应用程序上解析。当前的响应类结构有一个基类(BaseResponse)和许多(超过 25 个)子类,每种类型的请求对应于需要返回的不同事物。现在我正在寻找 protobuf 是否会比 XML 更快、更容易。据我了解,此类结构的 .proto 文件是:

Message BaseResponse {
Required Int field1 = 1;
Optional SubResponse1 sub1= 2;
Optional SubResponse2 sub2 = 3;
Etc....
}

Message SubResponse1 {
....
}

Message SubResponse2 {
....
}
Etc for each sub response.

我的问题是:如果我有超过 25 个这些可选元素(其中只有 1 个是非空的),这是否完全消除了使用 protobuf 的大小和性能优势?protobuf 对这个应用程序有意义吗?

4

1 回答 1

1

不,它不会影响性能优势——您只需要检查 Objective-C 代码中哪个是非空的。由于 protobuf 仅序列化非空值,因此它仍然非常有效。protobuf 规范本身实际上并不包括继承,所以你说你需要通过封装来欺骗它是对的 - 但既然你提到了 C#,请注意你所描述的(包括数据如何出现在网络上,即它将 100% 兼容)如果您使用 protobuf-net 作为 C# 实现,则可以通过继承直接完成 - 这对于您现有的模型应该是可能的。例如:

[ProtoContract]
[ProtoInclude(2, typeof(SubResponse1))]
[ProtoInclude(3, typeof(SubResponse2))]
public class BaseResponse
{
    // note Name and IsRequired here are optional - only
    // included to match your example
    [ProtoMember(1, IsRequired = true, Name="field1")]
    public int Field1 { get; set; }
    /*...*/
}
[ProtoContract]
public class SubResponse1 : BaseResponse
{/*...*/}
[ProtoContract]
public class SubResponse2 : BaseResponse
{/*...*/}

您可以通过以下方式获取 .proto:

var proto = Serializer.GetProto<BaseResponse>();

这使:

message BaseResponse {
   required int32 field1 = 1 [default = 0];
   // the following represent sub-types; at most 1 should have a value
   optional SubResponse1 SubResponse1 = 2;
   optional SubResponse2 SubResponse2 = 3;
}
message SubResponse1 {
}
message SubResponse2 {
}
于 2013-05-24T06:48:02.073 回答