Our system should accept user input from the terminal and match several well-known keywords (maybe 10).
We donβt have the space / computation to do the regular expression, etc., the code has to be tiny and fast.
Now, the nasty way to do this:
if(!strncmp(str,"hello",5)
{
do_hello();
}
else if(!strncmp(str,"world",5)
{
do_world();
}
else
{
meh();
}
So, after a few searches and reads, I am convinced that it is best to pre-compute the hash of various matches as int, and then simply use the case statement:
switch(hash(str))
{
case HASH_OF_HELLO:
do_hello();
break;
case HASH_OF_WORLD:
do_world();
break;
default:
meh();
break;
}
We can compute * HASH_OF_match * at compile time. This seems like a potentially faster / more elegant way to select a row from a relatively small set.
- ?/ ?/- ?
, , ;), dan bernstein, .
unsigned int
get_hash(const char* s)
{
unsigned int hash = 0;
int c;
while((c = *s++))
{
hash = ((hash << 5) + hash) ^ c;
}
return hash;
}