I have a code pattern which translates one integer to another. Just like this:
int t(int value) {
switch (value) {
case 1: return const_1;
case 3: return const_2;
case 4: return const_3;
case 8: return const_4;
default: return 0;
}
}
It has about 50 entries currently, maybe later on there will be some more, but probably no more than hundred or two. All the values are predefined, and of course I can order case labels by their values. So the question is, what will be faster – this approach or put this into hash map (I have no access to std::map, so I’m speaking about custom hash map available in my SDK) and perform lookups in that table? Maybe it’s a bit of premature optimization, though… But I just need your opinions.
Thanks in advance.
EDIT: My case values are going to be in range from 0 to 0xffff. And regarding the point of better readability of hash map. I’m not sure it really will have better readability, because I still need to populate it with values, so that sheet of constants mapping is still needs to be somewhere in my code.
EDIT-2: Many useful answers were already given, much thanks. I’d like to add some info here. My hash key is integer, and my hash function for integer is basically just one multiplication with integral overflow:
EXPORT_C __NAKED__ unsigned int DefaultHash::Integer(const int& /*aInt*/)
{
_asm mov edx, [esp+4]
_asm mov eax, 9E3779B9h
_asm mul dword ptr [edx]
_asm ret
}
So it should be quite fast.
A
switchconstruct is faster (or at least not slower).That’s mostly because a
switchconstruct gives static data to the compiler, while a runtime structure like a hash map doesn’t.When possible compilers should compile
switchconstructs 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.