c++ - Is stringstream better than string's operator '+' for string objects concatenation? -
for example, have 2 string objects:string str_1, str_2. want concatenate them. can use 2 methods: method 1:
std::stringstream ss; //std::string str_1("hello"); //std::string str_2("world"); ss << "hello"<< "world"; const std::string dst_str = std::move(ss.str());
method 2:
std::string str_1("hello"); std::string str_2("world"); const std::string dst_str = str_1 + str_2;
because string's buffer read only, when change string object, buffer destroy , create new 1 store new content. method 1 better method 2? understanding correct?
stringstreams
complex objects compared simple strings. everythime use method 1, stringstream
must constructed, , later destructed. if millions of time, overhead far neglectible.
the apparently simple ss << str_1 << str_2
in fact equivalent std::operator<<(sst::operator<<(ss, str_1), str_2);
not optimized in memory concatenation, common streams.
i've done small benchmark :
in debug mode, method 2 twice fast method1.
in optimized build (verifying in assembler file nothing optimized away), it's more 27 times faster.
Comments
Post a Comment