Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
struct hasher: public std::unary_function< const char, void > {
uint32 &res;
inline hasher(uint32 &inp): res(inp){};
inline void operator()( const char c ){res = 31*res + c;};
};
uint32 good_hash_stl(const std::string& str) {
uint32 h = 0;
for_each (str.begin(),str.end(), hasher(h));
return h;
}*************************************
string length: 8 bytes
const char*: 12.35 msec, hash: 312017024
std::string: 3.72 msec, hash: 312017024, 0.30x
propper stl approach: 2.88 msec, hash: 312017024, 0.23x
total allocs: 0
total deallocs: 0
*************************************
string length: 16 bytes
const char*: 19.55 msec, hash: 2657714432
std::string: 8.10 msec, hash: 2657714432, 0.41x
propper stl approach: 6.52 msec, hash: 2657714432, 0.33x
total allocs: 0
total deallocs: 0
*************************************
string length: 32 bytes
const char*: 34.42 msec, hash: 3820028416
std::string: 14.33 msec, hash: 3820028416, 0.42x
propper stl approach: 14.11 msec, hash: 3820028416, 0.41x
total allocs: 0
total deallocs: 0uint32 hash_c(const char* str) {
uint32 h = 0;
while (*str)
h = 31*h + *str++;
return h;
}
Немного о том, почему использование STL бывает неоптимальным