The advantages and disadvantages:

Advantages:

A. The data encoded by the data interface occupies a small memory space, about 30% to 40% of that of JSON. B. High transmission efficiency and low traffic consumption, because it is bytecode, encoding and decoding efficiency, and faster than JSON from bytecode to object stream. C. The security of the transmission process is also improved because it is bytecode and the packet grabber only captures binary data. D. Support multiple language compilation: C ++ Java Python C # and so on. E. Proto data structure file prepared, common to both front and back ends.Copy the code

Disadvantages:

A. Because it is a Product of Google, its versatility is relatively poor compared with XML and JSON. B. If the transmitted data and data structure are complex, compiling the data structure file of PROTO will be complicated and wordy, and teaching is prone to error.Copy the code

Usage Scenarios:

Protobuffer is used in many fields: data transmission, data communication for game development, data storage compression for big data, instant messaging IM (QQ, wechat)

The data type

In the IDL file of the protobuffer (INT32, INT64, uint32, uint64, SINT32, SINT64, bool, enum) the data types are encoded using varint

The detailed process of codec (for example) :

Varint encoding process: In Java, an int requires 4 bytes. Protobuf numbers less than 256 are represented by int32. Varint encoding requires only 1 byte. Although larger numbers require more bytes, statistics show that smaller numbers are most often the case, and varint encodings can represent numbers in fewer bytes, thus better compression of data.

Int32 studentNums = 300; 300 binary: Java int is 4 bytes, 32 bits // Convert 300 to binary 010 1100 // Take 7 bits from the end of the byte string bit 1010 1100 // Because there is data in the previous byte, So in this byte of the current 7-bit bit, the highest bits complement 1. Step 2: // Because there is no data in the previous byte, the highest bit of the string is filled with 0 step 3: Concatenate the bytes extracted from step 1 and step 2. Since the endian order is adopted, the lowest byte of step 1 is placed at the highest address. Step 2 Put the high-order bytes in the status address (Step 1) (Step 2) 1010 1100 ++ 000 0001 0 ===> 1010 1100 0000 0010 The 4-byte value of INT32:300 is compressed by varint encoding ==> 2 bytesCopy the code

Varint Decoded: 10101100 00000010(two byte array) ===> Decoded to: 300(4 bytes of raw data)

1010 1100 0000 0010 010 1100 000 0010 / / remove the highest level of each byte = = = = = = = = = = = = = = = = | | to two bytes exchange | | 000 0010 010 1100 / / exchange after removing the highs of two bytes | | / / code used little endian, and Java normal use is big endian read mode, so to swap bytes when decoding | | / / byte after the switch, 100101100 => 100101100 256 + 32 + 8 + 4 = 300Copy the code