So today I tried to optimize some code using std::string from the Standard Template Library and found something interesting.
Let's say you have strings to assign which sometimes get longer and then again shorter. To avoid unnecessary memory allocations you can use std::string::resize(size_t n); so you create the string and then resize it so that it is big enough for the longest string:
std::string s0; s0.resize(512); std::string s1="hello"; std::string s2=""; std::string s3="big"; std::string s4=""; std::string s5="world"; s0=s1; s0=s2; s0=s3; s0=s4; s0=s5;
So everything is handled as std::string and you might think everything's fine.
std::string s0; s0.resize(512); std::string s1="hello"; std::string s2=" "; std::string s3="big"; std::string s4=" "; std::string s5="world"; s0=s1.c_str(); s0=s2.c_str(); s0=s3.c_str(); s0=s4.c_str(); s0=s5.c_str();
Here everytime a standard C null-terminated string is assigned. You could think that this is slower, among others because the length is unknown and so during assignment either strlen() has to be called or every byte has to be checked for 0.
But, wrong !