首页 > 解决方案 > 列表中的性能过滤

问题描述

我有这段代码会执行得非常糟糕,越多的项目进入m_songs我正在寻找一些优化。内部 forloop 是这里的罪魁祸首,因为m_songs随着时间的推移,forloop 循环遍历所有项目以检查缓存中是否有某些项目。我将如何更有效地重写它?

for(auto& const filename : filenames) {
    auto alreadyInCache = false;
    for(unsigned int i = 0; i < m_songs.size(); i++) {
        if(filename == m_songs[i]->filename) {
            alreadyInCache = true;
        }
    }
    if(alreadyInCache) {
        continue;
    } else {
        // add items to m_songs;
    }
}

// Overwrite our cache with the latest m_songs

好的,我已经更新了我的代码以使用find_if()

在文件名的 forloop 中,我现在正在这样做:

auto it = std::find_if(m_songs.begin(), m_songs.end(), [filename](std::shared_ptr<Song> n) {
    return n->filename == filename;
});
auto alreadyInCache = it != m_songs.end();

if(alreadyInCache) continue;

这会更有效率吗?还能进一步改进吗?

标签: c++performancelistoptimization

解决方案


如果m_songs是一个 sorted vector,我假设它看起来就像填充它的相同代码( ),那么您可以使用而不是逐个元素检查// add items to m_songs来执行二进制搜索。std::lower_bound

如果您还没有按顺序添加元素,请按以下步骤操作:如何将值插入已排序的向量中?


推荐阅读