dahui
dahui

Reputation: 2166

Common proto3 fields with oneof or aggregation

I have to produce a proto class for an object which will have around 12 variations. All 12 variations share four fields which are the same, and then have specific fields. In most cases there will be many more non specific fields than there are common fields.

I was wondering what would be the most performant way to achieve this.

First option: defining the common fields in a common proto class and then declaring a field of this type in all the specific types:

message CommonFields {
    // common_field1
    // ... common_fieldN
}

message SpecificType1 {
    CommonFields common = 1;
    // specific fields...
}

Or would it be better to define one top level proto which contains the fields, and then having a oneof field, which can refer to another type containing the specific fields:

message BaseType {
    // common_field_1
    // ... common_field_N
    oneof specific_fields {
        SpecificTypeFields1 type1_fields = N;
        SpecificTypeFields2 type1_fields = N+1;
    }
}

message SpecificTypeFields1 {
    // specific fields...
}

message SpecificTypeFields2 {
    // specific fields...
}

I'm particularly interested in performance and also convention. Or if there are any more typical ways, such as just repeating the common fields.. Bearing in mind though my protos will only have 4 common fields, and typically 3-8 specific ones.

Upvotes: 2

Views: 2409

Answers (1)

jpa
jpa

Reputation: 12156

Depending on the protobuf library, there is usually some performance penalty for encoding submessages. For most libraries, such as the Google's own protobuf libraries, the difference is very small. With either of your options, you end up encoding 1 submessage per message, further reducing the impact.

I have seen both formats commonly used. If the decoder side already knows the message type (from e.g. rpc method name), aggregation is usually easier to implement as it doesn't require separately checking the oneof type.

However, if the message type is not known, oneof method is better as it allows easy detection of the type.

Upvotes: 1

Related Questions