devxlogo

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 < 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.

See also  Essential Measures for Safeguarding Your Digital Data
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist