Protocol buffers, also known as protobuf, are internally developed by Google to provide a better method of data serialization and deserialization compared to XML
.
Data serialization: the process to convert complex data type objects into a byte stream for transfer, storage, and distribution purposes on physical devices.
Data deserialization: the reverse process of creating objects from the byte sequence stream.
Google developed protocol buffers to make data serialization and deserialization simpler, smaller, faster, and more maintainable than JSON
, XML
, etc.
JSON
?JSON
(JavaScript Object Notation) is just text, and we can open any object with a text viewer and examine it at any point.
Let’s look at some advantages of using both protobuf and JSON
in any program.
Schemas: Protobuf uses a binary message format that allows programmers to specify a schema for the data.
Backward compatibility: Proto files can prevent errors and make rolling out new features and services much simpler than JSON
and XML
.
Validation and extensibility: The definitions of the required
, optional
, and repeated
keywords in protocol buffers are extremely powerful. They allow you to encode at the schema level.
Language interoperability: We can implement protocol buffers in a variety of languages. They make interoperability between
message person {
required string name = 0;
optional int32 Age = 1;
repeated string location = 2;
}
JSON
Readable: There remain times when JSON
is a better fit than protocol buffers, including situations where you need or want data to be human readable.
Browser: JSON
provides data exchange between your web application and the browser and server without the need to reload the page.
Javascript: When your server-side application is written in JS
: JavaScript.
person : {
"name": "Robin",
"Age": 40,
"location": "canada"
}
JSON
is simple to parse and generate. You can connect pieces written in different programming languages; “after all, it’s just a string.”
Protobuf is binary, so it doesn’t have the advantage of being easily portable on its own. So the creators decided to port it themselves by shipping generators for the most popular programming languages.
Based on the use cases, we can choose any one of them.
JSON
is great when you have small volumes of messages exchanged, when you
want to inspect the data, and when your messages are different from each other.
Protobuf is great when you exchange high volumes of the same type of message and when performance matters.
As a rule of thumb, I use JSON
if it’s something I’m sending to a browser, and I would use protobuf if I want to exchange messages between services.