Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast comparison of char arrays?

Tags:

c++

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.

like image 839
StackedCrooked Avatar asked May 28 '10 14:05

StackedCrooked


People also ask

How do you compare char arrays?

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.

Can you compare two char arrays?

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.

Which is faster string or char array?

So the character array approach remains significantly faster although less so.

Can you compare char arrays in C?

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.


1 Answers

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?

like image 163
SystematicFrank Avatar answered Oct 10 '22 03:10

SystematicFrank