Sign in to follow this  
Bad Ham

hash_map lookup vs switch statement - speed?

Recommended Posts

Hi everyone! I'm trying to measure the viability of using a stdext::hash_map instead of a switch statement in my event system. Basically an event listener is passed an event and told to handle it. There are two methods we can use from there. 1) (what I'm using now) A large switch statement covering each type of message that the listener could get. 2) (what I'm considering) A hashmap of types to member function pointers taking the event data (which handle the message) Now, I know that hash_map has an O(1) lookup time. So this would seem to indicate that after a certain length of switch statement, hash_map would be faster. However we have the added overhead now of an extra function call. Which would be the more efficient way to do this?

Share this post


Link to post
Share on other sites
Between the two, a hashmap is the cleaner and more extensible algorithmic construct therefore it is the better choice. What you are doing is known as premature optimization. Implement it the "clean" way. If you later find that the hash lookup is the bottleneck (through profiling and hard data) then you can consider other options.

However, if your message handling lookup is the bottleneck for your game/application then you either have the fastest application in the universe or your app is only doing event lookups and nothing else.

-me

Share this post


Link to post
Share on other sites
Switch statement is faster. It's hardcoded, inlined, possibly use-case optimized.

It's also poor design choice, since you'll be hard-coding everything.

As they say, there's no free lunch. How many messages are we talking here? 1 million/second? Or 100? If 100, then flexible system is better from design perspective.

Share this post


Link to post
Share on other sites
Nowhere near a million, almost certainly. I'll go with the hash map implementation then. Thanks for the comments! I always have a tendancy to overthink/overoptimize things. :P

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this