Improving Large Strings’ Performance

Improving Large Strings’ Performance

Certain applications make use of very long strings. For example, a single string may contain generated HTML pages, a chapter of a book, a textual database and so on. Usually, the application repeatedly concatenates new substrings to the original string. Consequently, the string must frequently reallocate storage to make room for additional characters. However, recurrent reallocation can dramatically degrade performance?especially when the resulting string is very long (say a few hundred thousands of characters). To avert recurrent reallocations, use the reserve() member function of std::string. The performance improvement gained this way is quite noticeable. In some cases, the execution time of loops that took minutes may be reduced to seconds. Here is an example that shows how to use std::string to preallocate sufficient storage:

 #include int main(void){  std::string s;  s.reserve(1000000); //measure execution time without this  for (int i = 0; i 

On my machine, this entire program executes within less than two seconds. However, without the reserve() call, the loop takes several minutes.


Share the Post: