我需要逐步构建一个字符串,并试图找到最佳方法。它可以增长的最大值是大约10k,因此计划做这样的事情:
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
可以从文件/ tcp conn或ftp读取,并在运行时决定。它接收const char *并将其放入一个字符串(我可以避免但为方便起见而留下它)
但是,我听说有一种非常有效的方法来处理字符串流,但不知道该怎么做。欣赏任何见解。
答案 0 :(得分:13)
对我来说非常棒。
不要进行优化,直到遇到性能问题并测量任何性能变化为止。如果没有意识到,你最终可能会变得更糟!
答案 1 :(得分:0)
对于对保留和不保留字符串之间的区别感兴趣的人,请考虑以下代码:
#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;
}
在第一种情况下,字符串是保留的,在第二种情况下不是。这产生了时间:
60
78
用-O2编译的g ++。