zoukankan      html  css  js  c++  java
  • 序列化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); // 
    即为换行
            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字节

  • 相关阅读:
    windows 7系统搭建PHP网站环境
    本机搭建PHP环境全教程(图文)
    cmd不是内部命令解决方法
    [Tex学习笔记]章节用罗马字母编号
    丁伟岳院士逝世 享年70岁
    2014年度江西省青年科学家培养对象名单(共36名)
    Alexander Grothendieck去世了
    [詹兴致矩阵论习题参考解答]序言
    2014-2015第一学期听课安排
    一个老和尚的真言
  • 原文地址:https://www.cnblogs.com/luckygxf/p/9214646.html
Copyright © 2011-2022 走看看