Reputation: 2108
I have tested c++ std::string.length()
vs strlen()
function on VS2017 as below. The result is:
what surprised me is that string.length()
is 7x slower than strnlen()
. But I suppose string.length()
is an O(1)
operation, and strlen()
is an O(n)
operation.
I have also tested it on GNU GCC v7.1.1 on coding ground
And it shows string.length()
is slight faster than strlen()
(not as much as I expected.)
Why is that? something wrong in my test code?
class stopwatch
{
public:
stopwatch()
{
start = std::chrono::system_clock::now();
}
~stopwatch()
{
auto end = std::chrono::system_clock::now();
auto elasped = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
cout << "elasped: " << elasped.count() << endl;
}
private:
chrono::system_clock::time_point start;
};
void test_std_str(const string& ss)
{
stopwatch sw;
const int max = 100000;
int sum = 0;
for (int i = 0; i < max; i++)
{
sum += ss.length();
}
cout<< "test_string: sum = " << sum << endl;
}
void test_c_str(const char* str)
{
stopwatch sw;
const int max = 100000;
int sum = 0;
for (int i = 0; i < max; i++)
{
sum += strlen(str);
}
cout << "test_c_str: sum = " << sum << endl;
}
int main()
{
std::string ss = "abcdef";
const char* str = "abcdef";
int x;
cin >> x;
if (x > 0)
{
ss = "helloworld";
str = "helloworld";
}
test_std_str(ss);
test_c_str(str);
return 0;
}
Upvotes: 2
Views: 769
Reputation: 2108
To answer my own question:
As suggested by @Ken Y-N and @PaulMcKenzie, I localize the scope of stopwatch
to exclude the time of cout
, and build it with Release
build. The result is make sense to me now!
Upvotes: 2