根据FlatBuffers documentation,默认值不会占用网络空间。我想测试一下,所以这是我的代码:
我正在使用以下架构:
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个字节)。我在做哪部分/理解错了?
答案 0 :(得分:1)
几乎没有序列化格式仅将数据类型的原始位保存到磁盘。如果这样做的话,将无法在扩展架构时具有向前/向后兼容性,也无法知道存在哪些字段,等等。
FlatBuffers特别是使用offset和vtables实现此功能,这会占用空间。它还使用对齐,以便可以将数据有效地读入内存。尽管随着数据变大,空间开销也会减少。
在您的情况下,您有8个字节的原始数据(该字节必须与短裤对齐),根表的vtable偏移量(4个字节),vtable(4个字段+ 2个固定值,每个16位,总计)最多12个字节)和根表偏移量(4个字节)。那将是28个字节,但它是24个字节,因为您没有使用所有字段。在32位和16位项目之间对齐时,也有很多丢失。
有关格式的更多信息,请阅读:https://google.github.io/flatbuffers/flatbuffers_internals.html