Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Beginner
Dec 12, 2001



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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 <string>
int main(void)
  std::string s;
  s.reserve(1000000); //measure execution time without this
  for (int i = 0; i < 100000; ++i) 
   s += "hello";

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






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date