473,606 Members | 2,453 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

strcmp() vs. std::string::op erator==

Hi,

I recently wrote two benchmark programs that compared if two strings
were equal: one was a C program that used C char arrays with strcmp(),
and the other was a C++ program that used std::strings with
operator==().

In both programs, the first string consisted of one million
characters (all the letter 'a'). The second string was always one
character longer than the first string (with the letter 'a' for all the
characters).

In the first program (which was written in C), the comparison was
done like this:

int same = strcmp(string1, string2) ? 0 : 1;

In the second program (which was written in C++), the comparison was
done like this:

bool same = (string1 == string2);

These comparisons were performed in a loop that looped a large number
of times. Then the programs were timed to see which ran faster.

I expected the C++ code to run much, much faster than the C code,
since I would think that the std::string::op erator==() method would
first check to see if string1.length( ) == string2.length( ) and return
false (since two strings of unequal length cannot be equivalent). This
should run much faster than C's strcmp() function, which has to run
until it finds the first unequal character (which, in this case, will
be the one-million-and-one-th character).

However, the results surprised me. The C++ code did indeed run
faster, but not by much. Apparently it's not checking the length of
the strings in the operator==() method.

In fact, by experimenting with different lengths of the strings, I
found that the C code (using strcmp()) would narrowly beat out the C++
code (using std::string::op erator==()) if the string sizes were 1000
characters or less, but the C++ code would consistently run faster (but
not my much) if the string sizes were 10,000 characters or longer.

Please correct me if I'm wrong, but wouldn't it make more sense for
the std::string::op erator==() method to check the sizes of the strings
before it proceeds to compare every character? I would think that it
would save a lot of processor time when comparing text from large files
with identical headers.

If you think I'm missing something obvious by making this argument,
please don't hesistate to educate me.

Thanks for any input.

-- Jean-Luc

Oct 4 '05 #1
3 17096
jl_p...@hotmail .com wrote:
Hi,

I recently wrote two benchmark programs that compared if two strings
were equal: one was a C program that used C char arrays with strcmp(),
and the other was a C++ program that used std::strings with
operator==().

In both programs, the first string consisted of one million
characters (all the letter 'a'). The second string was always one
character longer than the first string (with the letter 'a' for all the
characters).

In the first program (which was written in C), the comparison was
done like this:

int same = strcmp(string1, string2) ? 0 : 1;

In the second program (which was written in C++), the comparison was
done like this:

bool same = (string1 == string2);

These comparisons were performed in a loop that looped a large number
of times. Then the programs were timed to see which ran faster.

I expected the C++ code to run much, much faster than the C code,
since I would think that the std::string::op erator==() method would
first check to see if string1.length( ) == string2.length( ) and return
false (since two strings of unequal length cannot be equivalent). This
should run much faster than C's strcmp() function, which has to run
until it finds the first unequal character (which, in this case, will
be the one-million-and-one-th character).

However, the results surprised me. The C++ code did indeed run
faster, but not by much. Apparently it's not checking the length of
the strings in the operator==() method.

In fact, by experimenting with different lengths of the strings, I
found that the C code (using strcmp()) would narrowly beat out the C++
code (using std::string::op erator==()) if the string sizes were 1000
characters or less, but the C++ code would consistently run faster (but
not my much) if the string sizes were 10,000 characters or longer.

Please correct me if I'm wrong, but wouldn't it make more sense for
the std::string::op erator==() method to check the sizes of the strings
before it proceeds to compare every character? I would think that it
would save a lot of processor time when comparing text from large files
with identical headers.

If you think I'm missing something obvious by making this argument,
please don't hesistate to educate me.

Thanks for any input.

-- Jean-Luc


I think this is dependent on your standard library implementation. I
see that STL-port does length checking first.

Cheers! --M

Oct 4 '05 #2
jl*****@hotmail .com wrote:
If you think I'm missing something obvious by making this argument,
please don't hesistate to educate me.


You are missing to post the code of that benchmark.

--
Salu2
Oct 4 '05 #3
mlimber wrote:

I think this is dependent on your standard
library implementation. I see that STL-port
does length checking first.

Hey, thanks! I went to http://www.stlport.org/ and looked around at
the source code. Sure enough, the operator==() method (in a file named
"_string.h" of STLport) does look like it checks the length before
comparing:

{
return __x.size() == __y.size()
&& _Traits::compar e(__x.data(),
__y.data(),
__x.size()) == 0;
}

Of course, I still wonder why other implementations don't do the
same. I would think that the cost of comparing the size of the strings
is negligible, so I don't see any reason why it shouldn't be done.

Thanks again.

-- Jean-Luc

Oct 4 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
8160
by: Angus Leeming | last post by:
Hello, Could someone explain to me why the Standard conveners chose to typedef std::string rather than derive it from std::basic_string<char, ...>? The result of course is that it is effectively impossible to forward declare std::string. (Yes I am aware that some libraries have a string_fwd.h header, but this is not portable.) That said, is there any real reason why I can't derive an otherwise empty
2
5842
by: Matthias Käppler | last post by:
Hi, I just browsed libstdc++6-doc and stumbled over a string operation I haven't noticed before: string::push_back. If for example I want to append single characters to an std::string, which one would be better, or is there any difference at all: mystr.push_back( c ); or
4
2237
by: Matthias | last post by:
Now I am confused. I am doing a "less" comparison in my program between strings, to see which strings in some range precede others. This is my approach: class SortedByName { public: bool operator() (const boost::filesystem::path& lhs, const boost::filesystem::path& rhs) {
3
2834
by: Heiko Hund | last post by:
Hi, I do not understand the deeper reason for the following compiler error $ g++ test.cpp test.cpp: In function `int main()': test.cpp:41: error: `std::basic_string<char, std::char_traits<char>, std::allocator<char> >' is an inaccessible base of `Path' I'm using Debians
9
3292
by: Jim Langston | last post by:
#include <string> int main () { std::string MyString = "Testing"; MyString = " " + MyString; } This works in Microsoft Visual C++ .net 2003
84
15834
by: Peter Olcott | last post by:
Is there anyway of doing this besides making my own string from scratch? union AnyType { std::string String; double Number; };
10
9046
by: lovecreatesbea... | last post by:
Is it correct and safe to compare a string object with "", a pair of quotation marks quoted empty string?If the string object: s = ""; does s contain a single '\'? Is it better to use std::string::size or std::string::empty to deal with this condition? Thank you. string s = ""; if (s == ""); if (s.size == 0); if (s.empty());
4
11219
by: daroman | last post by:
Hi Guys, i've problem with my small C++ programm. I've just small template class which represetns a array, everything works fine up to combination with std::string. I did tried it with M$ VC++ and with GCC (Cygwin and Linux) and my problem is when i try do this int main(int argc, char **argv) { array<std::stringa(10); a = "Huhuhu"; <--- with gcc i got a crash !
16
3657
by: yu_kuo | last post by:
Is there any comparison data on perfomance difference between std::string and c style string? Or maybe if there are source code which could be used to measuer on different compiler/platform, in a systematic way?
0
8024
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
7959
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8449
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8432
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8310
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6781
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5466
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
1561
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1305
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.