序列化json和protobuf大小比较
使用protobuf序列化为二进制和json序列化字符串大小比较
代码demo
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字节
json:110字节,删掉空格还有100字节
Please call me JiangYouDang!