why c++ std::string.length() is slower than strlen() on VS2017?
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;
}
c++ string c-strings strlen
|
show 4 more comments
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;
}
c++ string c-strings strlen
1
Are you sure you are testinglength()and not the optimiser, or the default non-optimised code? The first test maybe has hidden initialisation costs, so what happens if you swap the order? Multiple runs on your coding.ground link gives widely varying results, because you are measuring wallclock time, not processor time.
– Ken Y-N
Nov 14 '18 at 1:42
@KenY-N Yes, I was just typing the same thing. Swapping the order shows the opposite results of what the OP sees.
– DeiDei
Nov 14 '18 at 1:46
Also, coding.ground allows me to add-O2, so we get 2 milliseconds for both, if we add an extra call totest_std_str()that serves to (I guess) initialisestd::coutbuffers, etc.
– Ken Y-N
Nov 14 '18 at 1:48
3
@ricky Yourstopwatchlocal variable is also timing thecoutcalls in each of those functions. So these results are basically meaningless, unless you localize the scope ofstopwatch. Example:{ stopwatch sw; ... /*code without the cout*/ } std::cout << .... That is what your test shoujld be doing.
– PaulMcKenzie
Nov 14 '18 at 1:59
2
@PaulMcKenzie You are right! localize the scope ofstopwatchmakestest_std_stroutput elasped: 0
– ricky
Nov 14 '18 at 2:04
|
show 4 more comments
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;
}
c++ string c-strings strlen
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;
}
c++ string c-strings strlen
c++ string c-strings strlen
edited Nov 14 '18 at 4:05
ricky
asked Nov 14 '18 at 1:37
rickyricky
7561824
7561824
1
Are you sure you are testinglength()and not the optimiser, or the default non-optimised code? The first test maybe has hidden initialisation costs, so what happens if you swap the order? Multiple runs on your coding.ground link gives widely varying results, because you are measuring wallclock time, not processor time.
– Ken Y-N
Nov 14 '18 at 1:42
@KenY-N Yes, I was just typing the same thing. Swapping the order shows the opposite results of what the OP sees.
– DeiDei
Nov 14 '18 at 1:46
Also, coding.ground allows me to add-O2, so we get 2 milliseconds for both, if we add an extra call totest_std_str()that serves to (I guess) initialisestd::coutbuffers, etc.
– Ken Y-N
Nov 14 '18 at 1:48
3
@ricky Yourstopwatchlocal variable is also timing thecoutcalls in each of those functions. So these results are basically meaningless, unless you localize the scope ofstopwatch. Example:{ stopwatch sw; ... /*code without the cout*/ } std::cout << .... That is what your test shoujld be doing.
– PaulMcKenzie
Nov 14 '18 at 1:59
2
@PaulMcKenzie You are right! localize the scope ofstopwatchmakestest_std_stroutput elasped: 0
– ricky
Nov 14 '18 at 2:04
|
show 4 more comments
1
Are you sure you are testinglength()and not the optimiser, or the default non-optimised code? The first test maybe has hidden initialisation costs, so what happens if you swap the order? Multiple runs on your coding.ground link gives widely varying results, because you are measuring wallclock time, not processor time.
– Ken Y-N
Nov 14 '18 at 1:42
@KenY-N Yes, I was just typing the same thing. Swapping the order shows the opposite results of what the OP sees.
– DeiDei
Nov 14 '18 at 1:46
Also, coding.ground allows me to add-O2, so we get 2 milliseconds for both, if we add an extra call totest_std_str()that serves to (I guess) initialisestd::coutbuffers, etc.
– Ken Y-N
Nov 14 '18 at 1:48
3
@ricky Yourstopwatchlocal variable is also timing thecoutcalls in each of those functions. So these results are basically meaningless, unless you localize the scope ofstopwatch. Example:{ stopwatch sw; ... /*code without the cout*/ } std::cout << .... That is what your test shoujld be doing.
– PaulMcKenzie
Nov 14 '18 at 1:59
2
@PaulMcKenzie You are right! localize the scope ofstopwatchmakestest_std_stroutput elasped: 0
– ricky
Nov 14 '18 at 2:04
1
1
Are you sure you are testing
length() and not the optimiser, or the default non-optimised code? The first test maybe has hidden initialisation costs, so what happens if you swap the order? Multiple runs on your coding.ground link gives widely varying results, because you are measuring wallclock time, not processor time.– Ken Y-N
Nov 14 '18 at 1:42
Are you sure you are testing
length() and not the optimiser, or the default non-optimised code? The first test maybe has hidden initialisation costs, so what happens if you swap the order? Multiple runs on your coding.ground link gives widely varying results, because you are measuring wallclock time, not processor time.– Ken Y-N
Nov 14 '18 at 1:42
@KenY-N Yes, I was just typing the same thing. Swapping the order shows the opposite results of what the OP sees.
– DeiDei
Nov 14 '18 at 1:46
@KenY-N Yes, I was just typing the same thing. Swapping the order shows the opposite results of what the OP sees.
– DeiDei
Nov 14 '18 at 1:46
Also, coding.ground allows me to add
-O2, so we get 2 milliseconds for both, if we add an extra call to test_std_str() that serves to (I guess) initialise std::cout buffers, etc.– Ken Y-N
Nov 14 '18 at 1:48
Also, coding.ground allows me to add
-O2, so we get 2 milliseconds for both, if we add an extra call to test_std_str() that serves to (I guess) initialise std::cout buffers, etc.– Ken Y-N
Nov 14 '18 at 1:48
3
3
@ricky Your
stopwatch local variable is also timing the cout calls in each of those functions. So these results are basically meaningless, unless you localize the scope of stopwatch. Example: { stopwatch sw; ... /*code without the cout*/ } std::cout << .... That is what your test shoujld be doing.– PaulMcKenzie
Nov 14 '18 at 1:59
@ricky Your
stopwatch local variable is also timing the cout calls in each of those functions. So these results are basically meaningless, unless you localize the scope of stopwatch. Example: { stopwatch sw; ... /*code without the cout*/ } std::cout << .... That is what your test shoujld be doing.– PaulMcKenzie
Nov 14 '18 at 1:59
2
2
@PaulMcKenzie You are right! localize the scope of
stopwatch makes test_std_str output elasped: 0– ricky
Nov 14 '18 at 2:04
@PaulMcKenzie You are right! localize the scope of
stopwatch makes test_std_str output elasped: 0– ricky
Nov 14 '18 at 2:04
|
show 4 more comments
1 Answer
1
active
oldest
votes
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!

add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53291954%2fwhy-c-stdstring-length-is-slower-than-strlen-on-vs2017%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
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!

add a comment |
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!

add a comment |
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!

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!

answered Nov 14 '18 at 4:05
rickyricky
7561824
7561824
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53291954%2fwhy-c-stdstring-length-is-slower-than-strlen-on-vs2017%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
Are you sure you are testing
length()and not the optimiser, or the default non-optimised code? The first test maybe has hidden initialisation costs, so what happens if you swap the order? Multiple runs on your coding.ground link gives widely varying results, because you are measuring wallclock time, not processor time.– Ken Y-N
Nov 14 '18 at 1:42
@KenY-N Yes, I was just typing the same thing. Swapping the order shows the opposite results of what the OP sees.
– DeiDei
Nov 14 '18 at 1:46
Also, coding.ground allows me to add
-O2, so we get 2 milliseconds for both, if we add an extra call totest_std_str()that serves to (I guess) initialisestd::coutbuffers, etc.– Ken Y-N
Nov 14 '18 at 1:48
3
@ricky Your
stopwatchlocal variable is also timing thecoutcalls in each of those functions. So these results are basically meaningless, unless you localize the scope ofstopwatch. Example:{ stopwatch sw; ... /*code without the cout*/ } std::cout << .... That is what your test shoujld be doing.– PaulMcKenzie
Nov 14 '18 at 1:59
2
@PaulMcKenzie You are right! localize the scope of
stopwatchmakestest_std_stroutput elasped: 0– ricky
Nov 14 '18 at 2:04