http://qs321.pair.com?node_id=11139006


in reply to Hash versus chain of elsifs

Is the set of strings fixed and known in advance?

If yes, look up minimal perfect hashing. One has to be generated specifically for your set of strings, and the generation part is usually expensive, but once it's done it can tell whether an input string is in the set with just one hash lookup and one string comparison.

Compilers and similar programs use this technique when they want to match tokens from the input stream against a small, known set of keywords.

I don't know if it's worth the effort, though, if you're working in Perl - just use a regular hash and be done with it. You may want to look at the problem again when you're optimizing your program, but you'll likely find that hash access is not your main bottleneck.