如何在不使用异常的情况下判断缓冲区是 Google 协议缓冲区 (Protobuf) 消息还是其他消息?
How to tell if a buffer is a Google Protocol Buffer (Protobuf) message or something else without using exceptions?
TLDR:我需要识别一个 byte[] 是否属于 protobuf 消息。有没有 try/catch 块的有效方法?
我正在将 protobuf 添加到 C# 消息监视应用程序的现有消息集中。我需要以 ~100Hz 的频率解析消息,我的消息集中大约有 40 条消息。目前我尝试使用以下代码解析 protobuf 消息:
public bool IsProtobuf(byte[] Data){
try
{
Any anyMsg = Any.Parser.ParseFrom(Data);
bool isProtobuf = anyMsg.Is(protobuf_message.Descriptor);
if(isProtobuf)
{
protobuf_message parsed = protobuf_message.Parser.ParseFrom(Data);
return true;
}
}
catch (InvalidProtocolBufferException)
{
return false;
}
}
然而 try/catch 块确实降低了我的表现。我从没有任何 protobuf 消息的 ~2000Hz 消息解析到包含我所有 protobuf 消息的 ~25Hz 消息解析。
有没有更快的方法来检查 byte[] 缓冲区是否属于 protobuf 消息?
评论总结了这一点,但这是您无需自己向 protobuf 消息添加标识符即可进行检查的最快方法。此外,只有像我在问题中记录结果时那样使用调试器 运行 时,性能影响才会显着。 运行 在单机中有更好的性能。
TLDR:我需要识别一个 byte[] 是否属于 protobuf 消息。有没有 try/catch 块的有效方法?
我正在将 protobuf 添加到 C# 消息监视应用程序的现有消息集中。我需要以 ~100Hz 的频率解析消息,我的消息集中大约有 40 条消息。目前我尝试使用以下代码解析 protobuf 消息:
public bool IsProtobuf(byte[] Data){
try
{
Any anyMsg = Any.Parser.ParseFrom(Data);
bool isProtobuf = anyMsg.Is(protobuf_message.Descriptor);
if(isProtobuf)
{
protobuf_message parsed = protobuf_message.Parser.ParseFrom(Data);
return true;
}
}
catch (InvalidProtocolBufferException)
{
return false;
}
}
然而 try/catch 块确实降低了我的表现。我从没有任何 protobuf 消息的 ~2000Hz 消息解析到包含我所有 protobuf 消息的 ~25Hz 消息解析。
有没有更快的方法来检查 byte[] 缓冲区是否属于 protobuf 消息?
评论总结了这一点,但这是您无需自己向 protobuf 消息添加标识符即可进行检查的最快方法。此外,只有像我在问题中记录结果时那样使用调试器 运行 时,性能影响才会显着。 运行 在单机中有更好的性能。