arrays - char * is slower than string in release compile c++ -
i made own string type in c++ , want test speed of string vs string in insert (equal =) action.
class mystring { private: char * _cont; public: mystring(const char * str) { size_t getlen = strlen(str); _cont = (char *) malloc(getlen + 1); memcpy(_cont, str, getlen); _cont[getlen + 1]= '\0'; } }; int main() { char * str = new char [12]; strcpy(str,"hello world"); auto start_t = chrono::high_resolution_clock::now(); (int = 0; < 10000000; i++) { string storage(str); } cout << chrono::duration_cast<chrono::milliseconds>(chrono::high_resolution_clock::now() - start_t).count() << " milliseconds\n"; start_t = chrono::high_resolution_clock::now(); (int = 0; < 10000000; i++) { mystring storage2(str); } cout << chrono::duration_cast<chrono::milliseconds>(chrono::high_resolution_clock::now() - start_t).count() << " milliseconds\n"; return 0; } in code created loop string char * str , same process own string variable in debug mode of compiler got result:
1108 milliseconds 531 milliseconds here string 2x faster standard string value (equal)
but found out 1 important thing .. when change compiler mode release, result diffrent ... string 5x faster
93 milliseconds 472 milliseconds what problem? why mystring 5x slower string in release mode? can fix it?
i realized if using
mystring(const char * str) { size_t getlen = strlen(str); char temp[getlen + 1]; memcpy(temp, str, getlen); _cont = temp; } mystring faster 2x in release mode when mystring() done, nothing save in char * _cont because function done , temp deleted auto ... there way action , hold temp in _cont after function done ?
why mystring 5x slower string in release mode?
probably because did not implement optimizations standard library does. micro benchmark particularly favorable small string optimization, implementation avoids allocating dynamic memory when string fits in space of string object itself.
what can fix it?
implement same optimizations standard library uses. again, why not use optimized string implementation?
i realized if using
char temp[getlen + 1]; memcpy(temp, str, getlen); _cont = temp;mystring faster 2x in release mode when mystring() done, nothing save in char * _cont because function done , temp deleted auto
the behaviour of accessing memory pointed _cont after function returns undefined. problem worse "nothing saved".
is there way action , hold temp in _cont after function done ?
no. there no way make prevent automatic array being destroyed @ end of scope. memory of string has either within string object, or allocated dynamically.
p.s string cheats in benchmark leaking allocated memory instead of releasing standard string does.
Comments
Post a Comment