I want to padding string
in C++,
Originally, just adding \0
to the end of the string directly.
paddingstr = "test";
for (int index = 0; index < 20000*1024; ++index){
paddingstr += '\0';
}
Then I find several ways to achieve my goal, and they are
- 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 to know which method is the most efficient. and then I compare them.
string paddingstr = "test";
__int64 before_run_t = GetTimeMs64();
string afterpadding = paddingstr.append(string(20000*1024, '\0'));
cout << "The run time of append is " << GetTimeMs64() - before_run_t << endl;
paddingstr = "test";
before_run_t = GetTimeMs64();
paddingstr.insert(paddingstr.end(), 20000*1024, '\0');
cout << "The run time of insert is " << GetTimeMs64() - before_run_t << endl;
paddingstr = "test";
before_run_t = GetTimeMs64();
for (int index = 0; index < 20000*1024; ++index){
paddingstr += '\0';
}
cout << "The run time of adding is " << 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 is " << GetTimeMs64() - before_run_t << endl;
And the result is
The run time of append is 60
The run time of insert is 3
The run time of adding is 8589
The run time of ostream is 2276
My question is that why insert is the fastest?
Update: the test codes are changed from
ss << 't' << std::setw(20000*1024) << std::setfill('\0');
paddingstr = ss.str();
Because of \0
is padding after the string, and the function str()
just return t
to paddingstr
, so the test result is not correct.