c++ - Why is 'insert' faster than 'append' in string padding? -



c++ - Why is 'insert' faster than 'append' in string padding? -

i want padding string in c++,

originally, adding \0 end of string directly.

paddingstr = "test"; (int index = 0; index < 20000*1024; ++index){ paddingstr += '\0'; }

then find several ways accomplish goal, ,

add-leading-zeros-to-string-without-sprintf padding-stl-strings-in-c c-can-setw-and-setfill-pad-the-end-of-a-string

i want know method efficient. , compare them.

string paddingstr = "test"; __int64 before_run_t = gettimems64(); string afterpadding = paddingstr.append(string(20000*1024, '\0')); cout << "the run time of append " << gettimems64() - before_run_t << endl; paddingstr = "test"; before_run_t = gettimems64(); paddingstr.insert(paddingstr.end(), 20000*1024, '\0'); cout << "the run time of insert " << gettimems64() - before_run_t << endl; paddingstr = "test"; before_run_t = gettimems64(); (int index = 0; index < 20000*1024; ++index){ paddingstr += '\0'; } cout << "the run time of adding " << gettimems64() - before_run_t << endl; ostringstream ss; before_run_t = gettimems64(); ss << 't' << std::setw(20000*1024) << std::setfill('a') << '\0'; paddingstr = ss.str(); cout << "the run time of ostream " << gettimems64() - before_run_t << endl;

and result is

the run time of append 60 run time of insert 3 run time of adding 8589 run time of ostream 2276

my question why insert fastest?

update: test codes changed from

ss << 't' << std::setw(20000*1024) << std::setfill('\0'); paddingstr = ss.str();

because of \0 padding after string, , function str() homecoming t paddingstr, test result not correct.

insert fastest because tell add together 20 mb of zeros @ once, , can allocate single time. append bit slower because has allocate 20 mb of zeros re-create them. loop slow because has reallocate more , more, @ to the lowest degree partially prepare if called paddingstr.reserve(20000*1024 + paddingstr.size()) first. , ostringstream slow because stringstreams slow, plus re-create string @ end.

c++ string padding

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -