martinus / robin-hood-hashing

Fast & memory efficient hashtable based on robin hood hashing for C++11/14/17/20
https://gitter.im/martinus/robin-hood-hashing
MIT License
1.5k stars 143 forks source link

What does unaligned_load do? #36

Closed tuket closed 5 years ago

tuket commented 5 years ago

More a question than an issue (sorry I couldn't figure out how to add labels in github).

I've been reading the source code and, even though there is a comment, I can't understand what is the purpose of this function.

template <typename T>
inline T unaligned_load(void const* ptr) noexcept {
    // using memcpy so we don't get into unaligned load problems.
    // compiler should optimize this very well anyways.
    T t;
    memcpy(&t, ptr, sizeof(T));
    return t;
}

Why not just do a cast?

*reinterpret_cast<T*>(ptr);

I've tried running both in my PC, and they seem to do the same, so may it's a performance thing?

Thanks for making this awesome piece of code :)

martinus commented 5 years ago

If you just have the *reinterpret_cast<T*>(ptr); and compile and run this for e.g. Solaris Sparc, and then try to use this on data that is not 64bit aligned, e.g. like this:

char const* str = "hello world";
uint64_t val = *reinterpret_cast<uint64_t*>(str+1);

Then your program will simply crash with a SIGBUS error. So it's not a performance thing, but a trick to be able to load possibly unaligned 64bit data on any CPU.

tuket commented 5 years ago

Wow, that's very interesting. Thanks for your answer