Gavin Lambert wrote:
On 9/06/2015 03:01, Anton Bachin wrote:
That's right, for now I am simply doing a linear scan through an array of strings. Changing the complexity to sub-linear is on my list of things to do, and I've considered those approaches (compile-time binary search, hashing, and trie).
Don't forget to measure performance. Given that enums tend to have a very low N, when I made a superficially similar static map with a runtime string index scan it turned out to be faster to just do the linear scan than to try to compute hashes or do more complex searches.
In my case I was processing a file with key-value data; I needed to convert the key string to an enum. There were about 25 keys that I was interested in. Initially I had a sequence of if statements each doing a std::string::operator==(const char*). I changed that to a switch statement on the first character, followed by std::string:: operator==(const char*) for each of the keys with that initial letter. This increased the speed of that code 50X, and the speed of the overall file processing 2X. It was definitely worthwhile. There is an important special case - when the string is not one of the valid keys. If this is frequent in a particular application, a linear scan will do especially badly. Regards, Phil.