Fast comparison of char arrays?

Posted by StackedCrooked on Stack Overflow See other posts from Stack Overflow or by StackedCrooked
Published on 2010-05-28T14:37:00Z Indexed on 2010/05/28 14:42 UTC
Read the original article Hit count: 178

Filed under:

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?

© Stack Overflow or respective owner

Related posts about c++