Jump to content
  • Advertisement
Sign in to follow this  
Bad Ham

hash_map lookup vs switch statement - speed?

This topic is 4141 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!