使用protobuf序列化爲二進制和json序列化字符串大小比較java
代碼demojson
package com.gxf.demo; import java.io.*; public class PtotobufDemo { public static void main(String[] args) throws IOException { AddressBookProtos.Person gxf = AddressBookProtos.Person.newBuilder() .setId(1234) .setName("guan xianseng") .setEmail("guanxianseng@example.com") .addPhones( AddressBookProtos.Person.PhoneNumber.newBuilder() .setNumber("555-4321") .setType(AddressBookProtos.Person.PhoneType.HOME)) .build(); String s = gxf.toString(); System.out.println("json length: " + s.length()); System.out.println(s); byte[] bytes = gxf.toByteArray(); String filePath = "./log"; File logFile = new File(filePath); OutputStream outputStream = new FileOutputStream(logFile); gxf.writeTo(outputStream); //json寫到文件 writeTextFile(s); System.out.println(bytes.length); } /** * 寫入文本文件 * */ private static void writeTextFile(String content) throws IOException { File writename = new File("./json.txt"); // 相對路徑,若是沒有則要創建一個新的output。txt文件 writename.createNewFile(); // 建立新文件 BufferedWriter out = new BufferedWriter(new FileWriter(writename)); out.write(content); // \r\n即爲換行 out.flush(); // 把緩存區內容壓入文件 out.close(); // 最後記得關閉文件 } }
proto文件緩存
syntax = "proto2"; package demo; option java_package = "com.gxf.demo"; option java_outer_classname = "AddressBookProtos"; message Person { required string name = 1; required int32 id = 2; optional string email = 3; enum PhoneType { MOBILE = 0; HOME = 1; WORK = 2; } message PhoneNumber { required string number = 1; optional PhoneType type = 2 [default = HOME]; } repeated PhoneNumber phones = 4; } message AddressBook { repeated Person people = 1; }
pb:58字節ui
json:110字節,刪掉空格還有100字節spa