c++ overhead from string concatenation -
i'm reading in text file of random ascii ifstream. need able put whole message string type character parsing. current solution works, think i'm murdering process time on more lengthy files using equivalent of this:
std::string result; (std::string line; std::getline(std::cin, line); ) { result += line; } i'm concerned overhead associated concatenating strings (this happening few thousand times, message 10's of thousands of characters long). i've spent last few days browsing different potential solutions, nothing quite fitting... don't know length of message ahead of time, don't think using dynamically sized character array answer.
i read through this thread sounded applicable still left me unsure;
any suggestions?
the problem don't know full size ahead of time, cannot allocate memory appropriately. expect performance hit related that, not way strings concatenated since efficiently done in standard library.
thus, recommend deferring concatenation until know full size of final string. is, start storing strings in big vector in:
using namespace std; vector<string> alllines; size_t totalsize = 0; // if can have access total size of data want // read (size of input file, ...) initialize totalsize // , use second code snippet below. (string line; getline(cin, line); ) { alllines.push_back(line); totalsize += line.size(); } then, can create big string knowing size in advance:
string finalstring; finalstring.reserve(totalsize); (vector<string>::iterator = alllines.begin(); != alllines.end(); ++its) { finalstring += *its; } although, should mention should only if experience performance issues. don't try optimize things not need to, otherwise complicate program no noticeable benefit. places need optimize counterintuitive , can vary environment environment. if profiling tool tells you need to.
Comments
Post a Comment