简体   繁体   English

比较字符串的瓶颈

[英]Bottleneck from comparing strings

This is a follow up question to Char* vs String Speed in C++ . 这是C ++中Char * vs String Speed的后续问题。 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;
}

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;
}

This will perform in O(log n) time rather than the O(n) you had before. 这将在O(log n)时间执行,而不是之前的O(n)。

There are other options if you have a sorted list, such as binary search . 如果您有排序列表,则还有其他选项,例如二进制搜索

If you often look up just a few different siteNumber and call it enough times it could be worthwile to implement a cache to store the latest siteNumber:s. 如果您经常查找几个不同的siteNumber并调用足够的次数,则可能有必要实现一个缓存来存储最新的siteNumber:s。 Although since you're only working in memory and not to/from disk I doubt it. 尽管由于您仅在内存中工作,而不是在磁盘中工作,但我对此表示怀疑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM