why c++ std::string.length() is slower than strlen() on VS2017?












2















I have tested c++ std::string.length() vs strlen() function on VS2017 as below. The result is:



msvs 2017



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.)



enter image description here



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;
}









share|improve this question




















  • 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 to test_std_str() that serves to (I guess) initialise std::cout buffers, etc.

    – Ken Y-N
    Nov 14 '18 at 1:48






  • 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








  • 2





    @PaulMcKenzie You are right! localize the scope of stopwatch makes test_std_str output elasped: 0

    – ricky
    Nov 14 '18 at 2:04
















2















I have tested c++ std::string.length() vs strlen() function on VS2017 as below. The result is:



msvs 2017



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.)



enter image description here



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;
}









share|improve this question




















  • 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 to test_std_str() that serves to (I guess) initialise std::cout buffers, etc.

    – Ken Y-N
    Nov 14 '18 at 1:48






  • 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








  • 2





    @PaulMcKenzie You are right! localize the scope of stopwatch makes test_std_str output elasped: 0

    – ricky
    Nov 14 '18 at 2:04














2












2








2








I have tested c++ std::string.length() vs strlen() function on VS2017 as below. The result is:



msvs 2017



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.)



enter image description here



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;
}









share|improve this question
















I have tested c++ std::string.length() vs strlen() function on VS2017 as below. The result is:



msvs 2017



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.)



enter image description here



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






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 14 '18 at 4:05







ricky

















asked Nov 14 '18 at 1:37









rickyricky

7561824




7561824








  • 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 to test_std_str() that serves to (I guess) initialise std::cout buffers, etc.

    – Ken Y-N
    Nov 14 '18 at 1:48






  • 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








  • 2





    @PaulMcKenzie You are right! localize the scope of stopwatch makes test_std_str output elasped: 0

    – ricky
    Nov 14 '18 at 2:04














  • 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 to test_std_str() that serves to (I guess) initialise std::cout buffers, etc.

    – Ken Y-N
    Nov 14 '18 at 1:48






  • 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








  • 2





    @PaulMcKenzie You are right! localize the scope of stopwatch makes test_std_str output 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












1 Answer
1






active

oldest

votes


















2














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!



enter image description here






share|improve this answer























    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
    });


    }
    });














    draft saved

    draft discarded


















    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









    2














    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!



    enter image description here






    share|improve this answer




























      2














      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!



      enter image description here






      share|improve this answer


























        2












        2








        2







        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!



        enter image description here






        share|improve this answer













        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!



        enter image description here







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 14 '18 at 4:05









        rickyricky

        7561824




        7561824






























            draft saved

            draft discarded




















































            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.




            draft saved


            draft discarded














            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





















































            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







            Popular posts from this blog

            List item for chat from Array inside array React Native

            Thiostrepton

            Caerphilly