1

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

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.

Community
  • 1
  • 1
zangw
  • 43,869
  • 19
  • 177
  • 214

1 Answers1

2

Insert is fastest because you tell it to add 20 MB of zeros all at once, and it can allocate a single time. Append is a bit slower because it has to allocate 20 MB of zeros then copy them. The loop is slow because it has to constantly reallocate more and more, which you could at least partially fix if you called paddingstr.reserve(20000*1024 + paddingstr.size()) first. And the ostringstream is slow because stringstreams are usually slow, plus you copy to the string at the end.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436