Ian is correct. In this specific case, you don't save any bytes. In
general, 25% of the time you'll save no bytes and 75% of the time you'll
save 8 bytes, for an average of 6 bytes.

In my opinion this usually isn't worth it, since it complicates application
code and is likely to lead to bugs.

-Kenton

On Sun, Mar 24, 2019 at 7:02 PM Ian Denhardt <[email protected]> wrote:

> As declared, it won't actually save *any* space, because the union tag
> will cause the size of the data section of your parent struct to grow to
> one word (instead of zero, since everything else is pointers), so with
> just the list pointer you have an extra word at the start of the struct
> list vs. a direct pointer to the struct, whereas with the union you have
> a bigger parent struct. If there were already other fields in the parent
> struct such that adding the union didn't grow the struct, you might see
> a marginal gain, but this feels like premature optimization to me.
>
> See also the encoding spec:
>
>     https://capnproto.org/encoding.html
>
> Quoting Cagatay K (2019-03-24 19:50:25)
> >    I have a case where a struct has a list of "child" structs, but the
> >    list almost always has a single element. Is there any benefit to using
> >    a union to switch between a list and a single element, like below?
> >    struct Parent {
> >    �  name: Text;
> >    �
> >    �  struct Child {
> >    �  �  id :UInt64;
> >    �  �  value: Text;
> >    �  }
> >    �  union {
> >    �  �  child :Child;
> >    �  �  children :List(Child);
> >    �  }
> >    }
> >    The idea is that a single child would take less space, be faster to
> >    access, may be stored in a more compact way if it's small (for some
> >    definition of small), etc. Or is this a pointless exercise because
> even
> >    if there was an effect it would have been too small to matter?
> >    Cheers,
> >    �CK.
> >
> >    --
> >    You received this message because you are subscribed to the Google
> >    Groups "Cap'n Proto" group.
> >    To unsubscribe from this group and stop receiving emails from it, send
> >    an email to [1][email protected].
> >    Visit this group at [2]https://groups.google.com/group/capnproto.
> >
> > Verweise
> >
> >    1. mailto:[email protected]
> >    2. https://groups.google.com/group/capnproto
>
> --
> You received this message because you are subscribed to the Google Groups
> "Cap'n Proto" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to [email protected].
> Visit this group at https://groups.google.com/group/capnproto.
>

-- 
You received this message because you are subscribed to the Google Groups 
"Cap'n Proto" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
Visit this group at https://groups.google.com/group/capnproto.

Reply via email to