JSON与Protocol Buffers同为序列化数据的存储格式。
性能比较,视平台、语言、数据结构复杂程度的不同,Protocol Buffers与JSON相比,性能可能会从慢15倍到快5倍。值得指出的是,在Android系统中,Protocol Buffers反序列化数据会比JSON快大约3倍[1]。
JSON数据格式有一个缺点:冗余太大,如:
每一条数据都要包括"Name"与"Gender",据统计,JSON格式的数据至少有1/5是无效的。
与JSON不同,Protocol Buffers用二进制编码数据,而且数据的格式是事先通过一个后缀名为.proto的文件指定的,如:
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的区别