【问题标题】:Why is the Protobuf blob heavier than the JSON equivalent?为什么 Protobuf blob 比等效的 JSON 更重?
【发布时间】:2023-01-29 04:36:03
【问题描述】:

我正在尝试使用 protobuf 来加速我的前端和后端之间的数据传输。

作为 POC,我尝试加载一个 JSON 文件,将其转换为 protobuf 缓冲区,并将结果保存在一个新文件中。

但事实证明,新文件比 JSON 文件重。我做错什么了吗?

这是我的文件:

// input.proto

syntax = "proto3";

message MyData {
    repeated float a = 1;
    repeated float b = 2;
    repeated float c = 3;
    float d = 4;
    repeated float e = 5;
}
// index.mjs

import protobuf from 'protobufjs';
import fs from 'fs';

protobuf.load('./input.proto', (err, root) => {
    const payload = JSON.parse(fs.readFileSync('./input.json', {encoding: 'utf8'}));

    var Message = root.lookupType("MyData");

    var errMsg = Message.verify(payload);
    if (errMsg)
        throw Error(errMsg);

    var message = Message.create(payload);
    const buffer = Message.encode(message).finish();

    fs.writeFileSync('./output.pb', buffer, 'binary');
}, () => {

});
// input.json
{
  "a": [1, 2.4, 3, 4],
  "b": [1, 2, 3, 4],
  "c": [1, 2, 3.2, 4],
  "d": 10.321,
  "e": [1, 2, 3.7, 4],
}

(我实际的 json 比那个大得多,但它遵循与这个相同的格式)


最后:

$ du -h input.json output.pb
2,0M    input.json
2,5M    output.pb

谢谢你的帮助!

【问题讨论】:

    标签: node.js json protocol-buffers protobuf.js


    【解决方案1】:

    原因可能是 Protocol Buffers 中的 float 被编码为 I32,所以每个数字需要 4 个字节。在 JSON (UTF8) 中,单个数字用 3 个字节(空格、数字和逗号)表示。您也可以省略空格,使 JSON 更加紧凑。

    【讨论】:

      猜你喜欢
      • 2018-09-08
      • 2017-04-14
      • 2020-05-17
      • 1970-01-01
      • 2018-01-21
      • 1970-01-01
      • 2018-03-02
      • 2023-03-18
      • 2020-01-02
      相关资源
      最近更新 更多