【问题标题】:Many subclasses for one base class - protobuf performance一个基类的许多子类 - protobuf 性能
【发布时间】:2013-05-24 14:48:02
【问题描述】:

现在我有一个应用程序,我的 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 对这个应用有意义吗?

【问题讨论】:

    标签: protocol-buffers protobuf-net


    【解决方案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 {
    }
    

    【讨论】:

      猜你喜欢
      • 2014-05-23
      • 1970-01-01
      • 2013-06-15
      • 1970-01-01
      • 1970-01-01
      • 2013-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多