PB vs XML vs JSON

JSONProtocol Buffers同为序列化数据的存储格式。

 

性能比较,视平台、语言、数据结构复杂程度的不同,Protocol Buffers与JSON相比,性能可能会从慢15倍到快5倍。值得指出的是,在Android系统中,Protocol Buffers反序列化数据会比JSON快大约3倍[1]

 

JSON数据格式有一个缺点:冗余太大,如:

 

[{ " Name " " Jane " " Gender " 0 }, { " Name " " Waith " " Gender " 1 }]

 

每一条数据都要包括"Name"与"Gender",据统计,JSON格式的数据至少有1/5是无效的。

 

与JSON不同,Protocol Buffers用二进制编码数据,而且数据的格式是事先通过一个后缀名为.proto的文件指定的,如:

 

message Person {
  required string Name 
=   2 ;
  optional int32 Gender 
=   3 ;
}

 

这样Protocol Buffers的数据会比JSON小不少,在一些场景,比如内存里要存储更多的数据时,用Protocol Buffers会更合适[2]


Protocol buffers have many advantages over XML for serializing structured data. Protocol buffers:

  • are simpler
  • are 3 to 10 times smaller
  • are 20 to 100 times faster
  • are less ambiguous
  • generate data access classes that are easier to use programmatically

For example, let's say you want to model a person with a name and an email. In XML, you need to do:

  <person>
    <name>John Doe</name>
    <email>jdoe@example.com</email>
  </person>

while the corresponding protocol buffer message (in protocol buffer text format) is:

# Textual representation of a protocol buffer.
# This is *not* the binary format used on the wire.
person {
  name: "John Doe"
  email: "jdoe@example.com"
}

When this message is encoded to the protocol buffer binary format (the text format above is just a convenient human-readable representation for debugging and editing), it would probably be 28 bytes long and take around 100-200 nanoseconds to parse. The XML version is at least 69 bytes if you remove whitespace, and would take around 5,000-10,000 nanoseconds to parse.

Also, manipulating a protocol buffer is much easier:

  cout << "Name: " << person.name() << endl;
  cout << "E-mail: " << person.email() << endl;

Whereas with XML you would have to do something like:

  cout << "Name: "
       << person.getElementsByTagName("name")->item(0)->innerText()
       << endl;
  cout << "E-mail: "
       << person.getElementsByTagName("email")->item(0)->innerText()
       << endl;

However, protocol buffers are not always a better solution than XML – for instance, protocol buffers would not be a good way to model a text-based document with markup (e.g. HTML), since you cannot easily interleave structure with text. In addition, XML is human-readable and human-editable; protocol buffers, at least in their native format, are not. XML is also – to some extent – self-describing. A protocol buffer is only meaningful if you have the message definition (the .proto file).



参考 

http://www.cnblogs.com/zhubo/archive/2011/07/06/json_and_protocolbuffers.html   与JSON的区别

https://developers.google.com/protocol-buffers/docs/overview    与XML的区别


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值