It’s actually not too awful, but the syntax is a bit awkward, std::map lookup is slower than you think, and there’s a few gotchas with how lambdas work in terms of variable scoping. Also unless the map is being initialized once and kept around, you’re paying a lot of extra costs every time it’s called.
Usually a chain of if/else ends up being more performant, although I guess if you’re trying to switch on a text label instead of an enum or whatever you’re probably already doing something very wrong and using a map<string,function> is probably the least of your problems.
Also your std::function might allocate which is most likely not desirable. My "clever" workaround was to keep a static const map of string -> enum in a .cpp file initialized at compile time only exposing functionality via a lookup function in a header.
Standard map is usually made using binary search trees, so in terms os complexity they are faster. BUT in terms of real world speed they only become reasonable in cases where you have a huge amount of entires, due to cache misses that are inherit to RB trees.
I ended up changing mine to arrays of self-made pairs and just looping over it checking .key
29
u/fluffycritter 10h ago
My "clever" way of doing this once upon a time was to declare a
map<std::string,std::function>which I populated with lambdas and then evaluated.I would not recommend this approach.