简体   繁体   中英

Performance comparison about template parameters of container?

I am developing an application that holds a vector of different types, like below

#include <vector>
#include <variant>
#include <any>

class Symbol{};
class Terminal : public Symbol{
    Token token;
};
class NonTerminal : public Symbol{};

Terminal main(){
    std::vector< std::any > vec1 = {Terminal(), NonTerminal()};                           // 1
    std::vector< std::variant<Terminal,NonTerminal> > vec2 = {Terminal(), NonTerminal()}; // 2
    std::vector<Symbol> vec3 = {Terminal(), NonTerminal()};                               // 3
}

where, Terminal and NonTerminal are derived classes of Symbol , from the basic theory of context-free language. Among the three vectors, Which is the fastest one, consider iterating the elements?

A critical problem is that the derived class Terminal holds an additional member variable token . An alternative implementation (my collegue's idea) would be something like below,

#include <vector>

class Symbol{
    bool isTerminal; // to differentiate Terminal and NonTerminal
    Token token;
};

Terminal main(){
    std::vector<Symbol> vec;
}

How about this?

They do different things, so it is meaningless to say which is faster.

vec1 discards the type information, so you have to remember that you put in Terminal then NonTerminal elsewhere.

vec2 retains all the information, so you can std::visit each element.

vec3 doesn't contain any Terminal or NonTerminal objects, it copied the Symbol base subobjects out of the values in the initialiser. Notably the token member of Terminal is not copied.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM