我有大量的对象要搜索。
数组有 > 60.000 个项目,搜索性能有时会非常慢。
该数组中的一个对象如下所示:
{
"title": "title"
"company": "abc company"
"rating": 13 // internal rating based on comments and interaction
...
}
我想搜索标题和公司信息,并按项目的评级排序。
这是我的搜索目前的样子:
onSearchInput(searchTerm) {
(<any>window).clearTimeout(this.searchInputTimeout);
this.searchInputTimeout = window.setTimeout(() => {
this.searchForFood(searchTerm);
}, 500);
}
searchForFood(searchTerm) {
if (searchTerm.length > 1) {
this.searchResults = [];
this.foodList.map(item => {
searchTerm.split(' ').map(searchTermPart => {
if (item.title.toLowerCase().includes(searchTermPart.toLowerCase())
|| item.company.toLowerCase().includes(searchTermPart.toLowerCase())) {
this.searchResults.push(item);
}
});
});
this.searchResults = this.searchResults.sort(function(a, b) {
return a.rating - b.rating;
}).reverse();
} else {
this.searchResults = [];
}
}
问题:有什么方法可以提高搜索逻辑和性能吗?
最佳答案
一堆提示:
- 将搜索 60,000 项放在前端有点过分。您可以通过任何方式在后端执行部分搜索吗?如果你真的必须在前端考虑搜索 block ,例如10,000,然后使用
setImmediate()
执行搜索的下一部分,这样用户的浏览器就不会在处理期间完全卡住。 - 在循环外对搜索词进行拆分和小写。
map()
就像您正在使用它一样奇怪,因为您不使用返回值。最好使用forEach()
。更好的是,使用filter()
来获取匹配的项目。- 在遍历搜索词时,使用
some()
(如评论中所指出的),因为这是提前返回的机会。 sort()
改变原始数组,因此您无需重新分配它。sort()
和reverse()
通常是一种气味。相反,将条件的两侧交换为b - a
。- 在这种规模下,使用
includes()
、indexOf()
、roll-your-own-for
进行性能测试可能有意义code>-loop,match()
(虽然几乎可以保证它会更慢)
关于javascript - 搜索大量对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53086149/