I'm implementing a simple hash map in C, and I thus implemented a generic and simple hash function which has the following implementation:
static inline int64_t hash(void_t *key, size_t ksize)
{
int64_t hash = 0;
char_t *key_str = key;
for (size_t i = 0; i < ksize; i++)
{
char_t c = key_str[i];
hash = 31 * hash + c;
}
return hash;
}
I wondered if it'd be better to implement it like:
static inline int64_t hash_x64(void_t *key, size_t ksize)
{
int64_t hash = 0;
size_t remain_ksize = ksize;
size_t i = 0;
while (remain_ksize >= sizeof(int64_t))
{
int64_t *val = key + i;
hash = 31 * hash + *val;
remain_ksize -= sizeof(int64_t);
i += sizeof(int64_t);
}
char_t *key_str = key;
for (; i < remain_ksize; i++)
{
char_t c = key_str[i];
hash = 31 * hash + c;
}
return hash;
}
Does this violate any alignment / aliasing rules? Is this code considered safe on x64 architectures? Would it execute faster on x64, or does the compiler already optimize the hash function for the underlying architecture?