Reputation: 5526
I need to progressively build a string and am trying to find the best way to do it. The maximum it can grow to is about 10k and hence was planning to do something like this:
const unsigned long long configSize = 10240; //Approximation
void makeMyConfig() {
std::string resp;
std::string input;
resp.reserve(configSize);
while ( getInput(input) ) {
resp += input;
}
if ( resp.length > configSize )
log << "May need to adjust configSize. Validate" << endl;
if (!sendConfig(resp)){
log << "Error sending config" << endl;
}
}
getInput
may read from file/tcp conn or ftp and is decided at runtime. It receives const char* and puts it into a string (which I may be able to avoid but left it for convenience)
However, I heard there is a much efficient way of doing with string streams but not sure how to do. Appreciate any insights.
Upvotes: 2
Views: 304
Reputation:
For anyone interested in the difference between reserving and not reserving a string, consider this code:
#include <iostream>
#include <string>
#include <ctime>
using namespace std;
const int BIG = 10000000;
const int EXTRA = 100;
int main() {
string s1;
s1.reserve( BIG );
clock_t t = clock();
for ( int i = 0; i < BIG + EXTRA; i++ ) {
s1 += 'x';
}
cout << clock() - t << endl;
string s2;
t = clock();
for ( int i = 0; i < BIG + EXTRA; i++ ) {
s2 += 'x';
}
cout << clock() - t << endl;
}
In the first case, the string is reserved, in the second not. This produces the timings:
60
78
for g++ compiled with -O2.
Upvotes: 0
Reputation: 23398
Looks pretty great to me.
Don't optimize until you actually have a performance problem and can measure any performance changes. You might end up making it worse without realizing!
Upvotes: 13