The Digital Lumberjack

Hacking Code When Life Goes Digital

Fast comparison of char arrays?


Post date 28 May 2010
Filed under

The following post is an extract from a Stack Overflow question and was automatically generated with the web scraping scripts at scraps.

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()

  1. It is more portable
  2. I usually try not to be smarter than my compiler/language. You are trying to compare memory contents and (depending on compiler options too) the implementation of memcmp() should be the most efficient way to do that.

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?

blog comments powered by Disqus