• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 233
  • Last Modified:

Speed question regarding 'string' type


I have a method which receives data 1024 bytes at a time.  The bytes are received in a 'char' buffer and appended to 'string' using the 'string' class' append() method.  If I receive 20MB of data, appending these 1024 byte buffers to the string takes a very long time (at least 5 minutes).  I was wondering if there was a more efficient way of doing this without knowing how much memory to allocate for the string (i.e., the 20 MB size is unknown).  Perhaps I could use strcat and append two 'char's and once the transmission is complete, copy the 'char' buffer into the string?  Should I use something more low level like a bstr?

As always, your help is much appreciated.
  • 2
2 Solutions
Hi StanChart,
> >Should I use something more low level like a bstr?

A low level method wouldn't help you here.
To speed it up, you need to be able to determined at runtime your approximate max size.
You can then call CString::GetBuffer(MaxValue), and then call ReleaseBuffer
That should reserve your reqired buffer size, and limit the amount of times the buffer has to resize and recopy the data.

David Maisonave :-)
Use string::reserve function to allocate large block of memory and string::capacity to test current memory block available for the string. In your case, every call to append requires reallocaltion and copying of the whole string.

// suppose I want to append 1024 bytes to string str
if ( str.capacity() < str.length() + 1024 )
    str.reserve(str.length() + 102400);   // will be enough for 100 next append calls

If you're looking for speed, in general, CString peformance faster then std::string that comes with VC++.

StanChartAuthor Commented:
You guys are really good! It's A LOT faster!!!
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now