I’m currently working in a codebase where IPv4 addresses are represented as pointers to u_int8. The equality operator is implemented like this:
bool Ipv4Address::operator==(const u_int8 * inAddress) const
{
return (*(u_int32*) this->myBytes == *(u_int32*) inAddress);
}
This is probably the fasted solution, but it causes the GCC compiler warning:
ipv4address.cpp:65: warning: dereferencing type-punned pointer will break strict-aliasing rules
How can I rewrite the comparison correctly without breaking strict-aliasing rules and without losing performance points?
I have considered using either memcmp or this macro:
#define IS_EQUAL(a, b) \
(a[0] == b[0] && a[1] == b[1] && a[2] == b[2] && a[3] == b[3])
I’m thinking that the macro is the fastest solution.
What do you recommend?
Update
I just read the article Squeezing performance out of memcmp usage which explains how the compiler (Visual Studio, but perhaps also GCC) can optimize !memcmp(..) calls.
I would go for memcmp()
Also think that if your compiler does not inline memcmp() you will suffer the function context switch
Are you sure you need to optimize that hard? Have you already checked that your program spend most of its time doing that type of operations?