javascript - 搜索大量对象

标签 javascript typescript search

我有大量的对象要搜索。

数组有 > 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/

相关文章:

javascript - 当我动态更改 html 时,ng-bind-html 中的 ng-click 不触发

javascript - Chrome 不在来自 iframe 的 ajax 请求中添加 header ,Firefox ok

html - Angular 2 typescript :How to show dropdown and textbox based on radio button

java - 对小文本进行有效搜索

c++ - 在 C++ 中搜索 CString

javascript - 有没有办法用 RequireJS 延迟设置资源的路径?

javascript - 在初始 .ajax 调用之外使用 JSON 数据 - 访问剩余的 JSON 数据

javascript - 如果文件存在于 asset 文件夹中,我们如何在 img 元素中设置 url

扩展面板标题内的 Angular Material 复选框 : how to allow the checkbox to be activated with the keyboard?

emacs - 使用 Emacs (windows) 和 GnuWin32 Grep 失败的 Grep