【发布时间】:2018-06-04 20:51:12
【问题描述】:
我有这段代码,如果进入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;
这会更有效吗?是否可以进一步改进?
【问题讨论】:
-
您考虑过使用
set/map/unordered_set/unordered_map吗? -
@NathanOliver 我没有,因为我对 c++ 很不熟悉,谢谢,我会调查一下!
-
@NathanOliver 在水下它是一个包含自定义类的共享指针的向量。我已经通过
find_if()的尝试更新了我的问题,还有什么可以改进的吗? -
如果你可以使用唯一的指针。但我担心你需要一个高级的字符串比较功能。
标签: c++ performance list optimization