C#:FlatBuffers 结果太大

C#: FlatBuffers results are too big

根据 FlatBuffers documentation,默认值不使用 space。我想对此进行测试,所以这是我的代码:

我正在使用这个架构:

table FlatCard
{
    cardIndex:ushort;
    level:byte = 1;
    damage:ushort;
    health:ushort;
}

root_type FlatCard;

这是 C# 代码:

var builder = new FlatBufferBuilder(1);
FlatCard.StartFlatCard(builder);
FlatCard.AddDamage(builder, 10);
Offset<FlatCard> offset = FlatCard.EndFlatCard(builder);
FlatCard.FinishFlatCardBuffer(builder, offset);
byte[] bytes = builder.SizedByteArray();
Console.WriteLine(bytes.Length);

实际结果是24,但我预计最多是7(3 ushort 和1 byte)。我的哪一部分 doing/understanding 错了?

几乎没有序列化格式只将数据类型的原始位保存到磁盘。如果这样做,那么在扩展架构时将无法获得 forwards/backwards 兼容性,也无法知道存在哪些字段等。

FlatBuffers 特别使用偏移量和 vtables 来实现此功能,其成本为 space。它还使用对齐方式,因此可以有效地将数据读入内存。 space 开销会随着数据变大而减少。

在你的情况下,你有 8 个字节的原始数据(字节必须与短裤对齐),一个 vtable 根偏移量 table(4 个字节),一个 vtable(4 个字段 + 2 个固定字段,每个字段 16 位,共 12 个字节)和根 table 偏移量(4 个字节)。那将是 28 个字节,但它是 24 个,因为您没有使用所有字段。在 32 位和 16 位项目之间的对齐中也丢失了一些信息。

有关格式的更多信息,请阅读:https://google.github.io/flatbuffers/flatbuffers_internals.html