dcsimg
Login | Register   
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


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

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


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.

 

 

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