4 ms·
it's not only type-safe, it uses much less memory, takes less time to construct and does not duplicate the "null" state: - your JSONStruct takes 160 bytes (on
by jcelerier 5y ago
it's not only type-safe, it uses much less memory, takes less time to construct and does not duplicate the "null" state:
- your JSONStruct takes 160 bytes (on 64-bit systems with libstdc++), the variant one takes 56, almost three times less.
- it needs std::optional<T> for each member to avoid construction, while std::variant does that by default. But the compiler still have to initialize all these optionals to their default state.
- you need on every access two branches:
* one for the type switch
* one for the optional
the variant only has one level of indirection.
- eatonphil 5y agoThat's fair. I assumed it would be clear to anyone who knows C++ better than I that the point of this post wasn't exactly performance. Actually I was most interested in just how simple and readable I could make it. But I didn't say that in the post anywhere. Will add.
- jcelerier 5y ago> I assumed it would be clear to anyone who knows It's just not possible to assume that at all on the internet. Every year I have students who learn from blog posts like this for instance.
- gravypod 5y agoAs someone who does quite a bit of C++ recently: for most uses readability is king. If you did want squeeze out the extra performance you could also do something where you store `std::variant<>` inside a struct and provide an API like this: if (auto int_value = value.i()) { // *int_value == your int } and expose a `std::variant<> &variant();` for use cases where you want the more complex/faster stuff.
- tcbawo 5y agoUsing variant as the storage type while providing a nice public accessor API makes sense given the huge difference in semantics between a struct containing optional fields and a variant.
- bialpio 5y agoPerformance aside, using variant has an added benefit of making illegal states unrepresentable. Optionals + an enum still allows users to either nullopt all the members, or have more than one member that is not nullopt.
- DilutedCoke 5y agoHow do you get the size of the struct? Is there a compiler command to do that?
- anonymoushn 5y agohttps://en.cppreference.com/w/cpp/language/sizeof https://en.cppreference.com/w/cpp/language/sizeof