比较字符串的瓶颈 [英] Bottleneck from comparing strings
本文介绍了比较字符串的瓶颈的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是针对 Char * vs String Speed in C ++ 的后续问题。
我已声明以下变量:
This is a follow up question to Char* vs String Speed in C++. I have declared the following variables:
std::vector<std::string> siteNames_;
std::vector<unsigned int> ids_;
std::vector<std::string> names_;
我把这个函数称为数万次,是一个主要的瓶颈。有更有效的方式来比较字符串吗?答案必须是跨平台兼容。
I call this function tens of thousands of times and is a major bottleneck. Is there a more efficient way to compare strings? The answer must be cross-platform compatible.
unsigned int converter::initilizeSiteId(unsigned int siteNumber){
unsigned int siteId = 0;
for (unsigned int i = 0; i < ids_.size(); i ++){
if (siteNames_[siteNumber].compare(names_[i]) == 0){
siteId = ids_[i];
break; // Once found, will stop searching and break out of for loop
}
}
if (siteId == 0)
std::cerr << "Could not find ID for site number " << siteNumber << std::endl;
return siteId;
}
推荐答案
http://www.cplusplus.com/reference/stl/map/\">map 或无序映射。然后你可以这样做:
Use a map or unordered map instead. Then you can do this:
std::map<string, int>names_;
// ...
unsigned int converter::initilizeSiteId(unsigned int siteNumber){
unsigned int siteId = 0;
std::map<string, int>::iterator i = names_.find(siteNames_[siteNumber]);
if (i != names_.end()){
siteId = i->second;
}
else (siteId == 0)
std::cerr << "Could not find ID for site number " << siteNumber << std::endl;
return siteId;
}
这将在O(log n)时间执行,而不是O )。
This will perform in O(log n) time rather than the O(n) you had before.
如果您有排序列表,还有其他选项,例如二分查找。
There are other options if you have a sorted list, such as binary search.
这篇关于比较字符串的瓶颈的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文