Thans per tutti. Forse ero un po 'pigro. Ora ho dato il test del codice.
test 1: 158.751ms, così a lungo, mio dio!
int main()
{
chrono::high_resolution_clock::time_point begin_time = chrono::high_resolution_clock::now();
for(int i=0;i<100000;i++)
{
//string str_1("hello ");
//string str_2("world");
stringstream ss;
ss << "hello " << "world";
const string dst_str = ss.str();
}
chrono:: high_resolution_clock::time_point stop_time = chrono::high_resolution_clock::now();
chrono::duration<double> slapsed = duration_cast<duration<double>>(stop_time - begin_time);
cout << "time takes " << slapsed.count() * 1000 << "ms" << endl;
return 0;
}
test 2: 31.1946ms, più veloce!
int main()
{
chrono::high_resolution_clock::time_point begin_time = chrono::high_resolution_clock::now();
for(int i=0;i<100000;i++)
{
string str_1("hello ");
string str_2("world");
const string dst_str = str_1 + str_2;
}
chrono:: high_resolution_clock::time_point stop_time = chrono::high_resolution_clock::now();
chrono::duration<double> slapsed = duration_cast<duration<double>>(stop_time - begin_time);
cout << "time takes " << slapsed.count() * 1000 << "ms" << endl;
return 0;
}
test 3: uso boost :: 35.1769ms filesystem :: percorso, anche una buona scelta
int main()
{
chrono::high_resolution_clock::time_point begin_time = chrono::high_resolution_clock::now();
for(int i=0;i<100000;i++)
{
string str_1("hello ");
string str_2("world");
boost::filesystem::path dst_path(str_1);
dst_path += str_2;
const string dst = dst_path.string();
}
chrono::high_resolution_clock::time_point stop_time = chrono::high_resolution_clock::now();
chrono::duration<double> slapsed = duration_cast<duration<double>>(stop_time - begin_time);
cout << "time takes " << slapsed.count() * 1000 << "ms" << endl;
return 0;
}
La risposta è ovvia (vale a dire, il metodo # 2). Si evita la creazione di un 'stringstream' oltre ai due inserimenti più la chiamata a' .str() '. – 101010
@cwfighter Hai provato a profilare le due opzioni? –
C++! = C# o Java. Le stringhe C++ non sono immutabili. – dandan78