C++: What is faster – lookup in hashmap or switch statement?

A switch construct is faster (or at least not slower).

That’s mostly because a switch construct gives static data to the compiler, while a runtime structure like a hash map doesn’t.

When possible compilers should compile switch constructs into array of code pointers: each item of the array (indexed by your indexes) points to the associated code. At runtime this takes O(1), while a hash map could take more: O(log n) at average case or O(n) at worst case, usually, and anyway a bigger constant number of memory accesses.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)