Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

9
  • 27
    Switches based on any hashable object may be implemented very efficiently using a hash table – see .NET. So your reason isn't completely correct. Commented Dec 3, 2008 at 18:36
  • Yeah, and this is the thing I don't understand. Are they afraid hashing objects will, in the long run, become too expensive? Commented Dec 3, 2008 at 18:41
  • 4
    @Nalandial: actually, with a little effort on the part of the compiler, it's not expensive at all because when the set of strings is known, it's pretty easy to generate a perfect hash (this isn't done by .NET, though; probably not worth the effort, either). Commented Dec 3, 2008 at 20:53
  • 3
    @Nalandial & @Konrad Rudolph - While hashing a String (due to it's immutable nature) seems like a solution to this problem you have to remember that all non-final Objects can have their hashing functions overridden. This makes it difficult at compile time to ensure consistency in a switch. Commented Dec 3, 2008 at 22:01
  • 2
    You can also construct a DFA to match the string (like regular expression engines do). Possibly even more efficient than hashing. Commented Aug 22, 2011 at 17:30