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字节

  • 相关阅读:
    pixijs shader 制作百叶窗效果
    pixijs shader 贴图溶解效果教程
    shadertoy使用教程
    pixijs shader教程
    glsl shader简明教程系列1
    javascript判断mp3是否播放完
    wxWidgets Tutorial
    NYOJ 214 最长上升子序列nlogn
    解决codeforces访问慢的问题
    dp 斯特林数 HDU2512一卡通大冒险
  • 原文地址:https://www.cnblogs.com/luckygxf/p/9214646.html
Copyright © 2011-2022 走看看