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?