在 Protobuf 中将 Go 结构编码为映射键的最有效方法

The most efficient way to encode Go structs as map keys in Protobuf

据我了解,协议缓冲区不允许使用消息(因此 Go 结构)作为键:

Key in map fields cannot be float/double, bytes or message types.
message HashCoordinate {
    int32 x = 1;
    int32 y = 2;
}
message State {
    map<HashCoordinate, Entity> entities = 1;
}

解决方法是将 HashCoordinate 键存储为 JSON 字符串:

message HashCoordinate {
    int32 x = 1;
    int32 y = 2;
}
message State {
    map<string, Entity> entities = 1;
}

出于比较目的,这不如存储结构那样高效。是否有其他选项比将 HashCoordinates 序列化为字符串性能更高?

视情况而定;您对绩效的关注程度如何? (相对于可读性、以其他语言处理 protobuf 的能力等)。

例如,我希望有一个 uint64 键(example encoding) to perform well but this sacrifices readability. Alternatively you could use a nested map,但这需要两次查找。也许用您的数据对一些替代方案进行基准测试。

请注意您不是 optimising prematurely - 使用上述任何一种方法的缺点是 read/understand 原型文件更难。在这种情况下,我的默认方法是 return 一个切片(因此在 proto 文件中 repeated )并在收到时将其转换为地图,除非有令人信服的理由将其作为地图传输。