Click to See Complete Forum and Search --> : efficient string comparison


bruce_puckett
March 26th, 2006, 05:52 PM
Hi,

I've read that the function calls of the mem*() family (such as memcpy() and memcmp() ) are more efficient that the function calls of the str*() family (such as strcpy() and strcmp() ) becaue they do not require the additional overhead of checking for null string termination (see Efficient C++ by Bulka and Mayhew).

In general, if I did not know the string length, what function should I use for the best efficiency? strcmp() or the compare() function of the std::string class or something else?

Can any summarize some guiding wisdom?

Thanks,

Kheun
March 26th, 2006, 07:10 PM
I don't think you really have to worry about the performance of STL string since they are already designed with performance in mind. Anyway, take a look at the implementation of std::string::compare in VC7.


int compare(const _Myt& _Right) const
{ // compare [0, _Mysize) with _Right
return (compare(0, _Mysize, _Right._Myptr(), _Right.size()));
}

int compare(size_type _Off,
size_type _N0, const _Elem *_Ptr, size_type _Count) const
{ // compare [_Off, _Off + _N0) with [_Ptr, _Ptr + _Count)
if (_Mysize < _Off)
_String_base::_Xran(); // _Off off end
if (_Mysize - _Off < _N0)
_N0 = _Mysize - _Off; // trim _N0 to size

size_type _Ans = _N0 == 0 ? 0
: _Traits::compare(_Myptr() + _Off, _Ptr,
_N0 < _Count ? _N0 : _Count);
return (_Ans != 0 ? (int)_Ans : _N0 < _Count ? -1
: _N0 == _Count ? 0 : +1);
}


It can be easily seen that it is calling another overloaded compare member function that takes in the sizes of both string, which later invoked the highlighted portion for string comparsion. The highlighted portion actually passed in the minimum size of the 2 strings. Therefore, it can be inferred that the actually string comparsion is done without checking the NULL character.

exterminator
March 27th, 2006, 12:57 AM
Simple - just use the overloaded operator== for the standard string class:

std::string string1 = "something";
std::string string2 = "something else";
if (string1==string2)
{
std::cout << "strings are equal" << std::endl;
}
else
{
std::cout << "strings are not equal" << std::endl;
}

Paul McKenzie
March 27th, 2006, 04:37 AM
Can any summarize some guiding wisdom?Yes, and that is make the code work first. Then profile the code to see if there are any real bottlenecks. Attempting to prematurely optimize code "by sight" or "by feel" usually results in no optimizations, and worse, code that is so convoluted (because of the faux optimization) that it is near impossible to maintain the code if there is a bug.

Regards,

Paul McKenzie