1. 程式人生 > 其它 >protobuf和json字串大小對比

protobuf和json字串大小對比

json字串拼裝程式

package org.proto;

import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Test3 {

    public static void main(String[] args) {
        Random rand = new Random();

        List<MyPoint> list = new ArrayList<>();

        
for(int i=1000000;i<1500000;i++){ MyPoint myPoint = new MyPoint (); myPoint.setVin("M"+i); myPoint.setLng(11600000 + rand.nextInt(100000)); myPoint.setLat(3900000 + rand.nextInt(100000)); list.add(myPoint); } String str = JSON.toJSON(list).toString(); System.out.println(str.length()); }
public static class MyPoint { private String vin; private int lng; private int lat; public String getVin() { return vin; } public void setVin(String vin) { this.vin = vin; } public int getLng() { return
lng; } public void setLng(int lng) { this.lng = lng; } public int getLat() { return lat; } public void setLat(int lat) { this.lat = lat; } } }

json字串空間大小

protobuf的資料結構

option java_outer_classname = "TestProtoPoint2";
option java_package = "org.proto";

message Points{
    repeated MyPoint myPoint=1;
}

message MyPoint{
     optional string vin=1;
     optional int32 lng=2;
     optional int32 lat=3;
}

protobuf資料拼裝程式

package org.proto;

import java.io.FileOutputStream;
import java.util.Random;

public class Test2 {

    public static void main(String[] args) throws Exception{

        final TestProtoPoint2.Points.Builder builder = TestProtoPoint2.Points.newBuilder();

        Random rand = new Random();

        for(int i=1000000;i<1500000;i++){
            TestProtoPoint2.MyPoint.Builder myPoint = TestProtoPoint2.MyPoint.newBuilder();

            myPoint.setVin("M"+i);

            myPoint.setLng(11600000 + rand.nextInt(100000));
            myPoint.setLat(3900000 + rand.nextInt(100000));

            builder.addMyPoint(myPoint);
        }

        byte[] bs = builder.build().toByteArray();

        FileOutputStream fos = new java.io.FileOutputStream("d:/test.pbf");

        fos.write(bs);
        fos.flush();
        fos.close();

        System.out.println(bs.length);
    }
}

protobuf序列號空間佔用大小