efficient string comparison
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,
Re: efficient string comparison
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.
Code:
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.
Re: efficient string comparison
Simple - just use the overloaded operator== for the standard string class:
Code:
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;
}
Re: efficient string comparison
Quote:
Originally Posted by bruce_puckett
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