I’m writing a simple parser in C++ that works using a map of string ‘triggers’ to ‘handler’ function pointers, my question is what would be the most ‘static’ and efficient method of implementing generation and access to the map?
I first considered a method, e.g. Parser::add_handler, that would add the trigger/handler to the parser’s map, but, as far as I know, this would need to be executed every time the program was ran whilst the data is known at compile time. (Although on the plus side, they would only need executed once, and not for each instantiated Parser.)
I then thought of using a virtual method, e.g. Parser::get_handlers in Parser that would be implemented in derived classes to return the handler map for that parser. This seems like a more nicely encapsulated solution although it would require a virtual function call for every created instance of the parser, with at least one call to the parser’s map-generating function.
Using the latter approach seems preferable at the moment, but it still leaves the map to be generated dynamically on each execution, is there away to avoid this?
If you don’t want to build the map dynamically, you can use a sorted static array with
std::lower_boundto search it in O(log n) time.If you have a good hash map implementation available, you might find that the overhead of populating it is less than the performance gain at runtime, depending on how many lookups you need to do.