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.
Arrays. equals() method. This method returns true if the arrays are equal and false otherwise. The two arrays are equal if they contain the same number of elements in the same order.
equals(char[] a, char[] a2) method returns true if the two specified arrays of chars are equal to one another. Two arrays are equal if they contain the same elements in the same order. Two array references are considered equal if both are null.
So the character array approach remains significantly faster although less so.
The strcmp() function is a built-in library function in the C language. Its basic role is to compare two character arrays or strings terminated by null value (C-strings) lexicographically. The strcmp() function is called using two character arrays as parameters and returns an integer value.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With