std::visit
seems to lack some optimizations yet on some implementations. That being said there’s a central point thats not very well seen in this lab-like setup – which is that variant based design is stack based vs. the virtual inheritance pattern which will naturally gravitate towards being heap based. In a real world scenario this means the memory layout could very well be fragmented (perhaps over time – once objects leave the cache, etc.) – unless it can somehow be avoided. The opposite is the variant based design that can be layout in contigoues memory. I believe this is an extremely important point to consider when performance is concerned that cannot be underestimated.
To illustrate this, consider the following:
std::vector<Base*> runtime_poly_;//risk of fragmentation
vs.
std::vector<my_var_type> cp_time_poly_;//no fragmentation (but padding 'risk')
This fragmentation is somewhat difficult to built into a benchmark test like this one.
If this is (also) within the context of bjarne’s statement is not clear to me when he said it could potentially be faster (which I do believe holds true).
Another very important thing to remember for the std::variant
based design is that the size of each element uses up the size of the largest possible element. Therefore if objects do not have roughly the same size this has to be considered carefully since it may have a bad impact on the cache as a result.
Considering these points together it’s hard to say which is best to use in the general case – however it should be clear enough if the set is a closed ‘smallish’ one of roughtly the same size – then the variant style shows great potential for being faster (as bjarne notes).
We now only considered performance and there are indeed other reasons for choosing one or the other pattern: In the end, you just have to get out the comfort of the ‘lab’ and design and benchmark your real world use cases.