What the best ways to use decimals and datetimes with protocol buffers?

前端 未结 4 2025
后悔当初
后悔当初 2021-02-08 14:56

I would like to find out what is the optimum way of storing some common data type that were not included in the list supported by protocol buffers.

  • datetime (secon
4条回答
  •  死守一世寂寞
    2021-02-08 15:29

    The protobuf design rationale is most likely to keep data type support as "native" as possible, so that it's easy to adopt new languages in future. I suppose they could provide in-build message types, but where do you draw the line?

    My solution was to create two message types:

    DateTime
    TimeSpan
    

    This is only because I come from a C# background, where these types are taken for granted.

    In retrospect, TimeSpan and DateTime may have been overkill, but it was a "cheap" way of avoiding conversion from h/m/s to s and vice versa; that said, it would have been simple to just implement a utility function such as:

    int TimeUtility::ToSeconds(int h, int m, int s)
    

    Bklyn, pointed out that heap memory is used for nested messages; in some cases this is clearly very valid - we should always be aware of how memory is used. But, in other cases this can be of less concern, where we're worried more about ease of implementation (this is the Java/C# philosophy I suppose).

    There's also a small disadvantage to using non-intrinsic types with the protobuf TextFormat::Printer; you cannot specify the format in which it is displayed, so it'll look something like:

    my_datetime {
        seconds: 10
        minutes: 25
        hours: 12
    }
    

    ... which is too verbose for some. That said, it would be harder to read if it were represented in seconds.

    To conclude, I'd say:

    • If you're worried about memory/parsing efficiency, use seconds/milliseconds.
    • However, if ease of implementation is the objective, use nested messages (DateTime, etc).

提交回复
热议问题