1

I checked the performance comparison for the below two programs in c++. One program loading strings into a string by string concatenation. Another one loading strings into a ostringstream buffer.

By String:

    string mytext = "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789";
    string res;

    clock_t tStart = clock();
    for(size_t i=0;i<10000000;++i) { res += mytext; }

    fprintf(stderr,"Time taken  To Load: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);
    tStart = clock();
    cout<<res<<endl;

    fprintf(stderr,"Time taken To Print: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);

Result:

Time taken  To Load: 3.31s
Time taken To Print: 1.37s

By Ostringstream:

string mytext = "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789";

clock_t tStart = clock();

std::ostringstream buffer;

for(size_t i=0;i<10000000;++i) { buffer<<mytext; }

fprintf(stderr,"Time taken To Load: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);
tStart = clock();
cout<<buffer.str()<<endl;

fprintf(stderr,"Time taken To Print: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);

Result:

Time taken To Load: 2.55s
Time taken To Print: 2.97s

From the above result of the two programs, I found loading data in string append is slower than ostringstream. But When printing the result, ostringstream took more time than string print.

My Question is, How can I reduce time in loading data in string stream and printing data using ostringstream? Is there any other way to do this process faster than these two methods?

Smith Dwayne
  • 2,675
  • 8
  • 46
  • 75
  • http://stackoverflow.com/questions/19844858/c-stdostringstream-vs-stdstringappend – Alexander Anikin Apr 12 '17 at 09:14
  • Possible duplicate of [c++ std::ostringstream vs std::string::append](https://stackoverflow.com/questions/19844858/c-stdostringstream-vs-stdstringappend) – cbuchart Oct 11 '19 at 14:24

0 Answers0