Javascript 如何提高数组搜索功能的速度?

Javascript 如何提高数组搜索功能的速度?,javascript,arrays,react-native,search,expo,Javascript,Arrays,React Native,Search,Expo,我正在使用react native编写字典应用程序 当我想从搜索框中过滤数组时,我写了下面的函数。当我使用2000单词列表进行测试时,这是非常好的。但是当单词列表达到数千个时,搜索速度真的很慢 那么,我如何改进这个搜索功能呢 //Filter array when input text (Search) let filteredWords = [] if(this.state.searchField != null) { filteredWords = this.state.glossar

我正在使用react native编写字典应用程序

当我想从搜索框中过滤数组时,我写了下面的函数。当我使用2000单词列表进行测试时,这是非常好的。但是当单词列表达到数千个时,搜索速度真的很慢

那么,我如何改进这个搜索功能呢

//Filter array when input text (Search)

let filteredWords = []
if(this.state.searchField != null)
{
  filteredWords = this.state.glossaries.filter(glossary => {
    return glossary.word.toLowerCase().includes(this.state.searchField.toLowerCase());
  })
}
由于这个问题似乎属于CodeReview,我认为您可以做一些事情来大幅加快代码速度[需要引用]:

  • 缓存对
    this.state.searchField.toLowerCase()的调用,因为您不需要在每次迭代中调用它
  • 循环使用常规的
    ,而不是华丽但缓慢的
    数组
    函数
以下是最终结果:

let filteredWords = []
if(this.state.searchField != null) {
    let searchField = this.state.searchField.toLowerCase(),
        theArray = this.state.glossaries;                          // cache this too

    for(let i = 0, l = theArray.length; i < l; ++i) {
        if(theArray[i].word.toLowerCase().includes(searchField)) {
            filteredWords.push(theArray[i]);
        }
    }
}

有多个因素使此代码变慢:

  • 您正在对lambda使用
    filter()
    。这会为正在搜索的每个项增加函数调用开销
  • 在调用
    includes()
    之前,您正在两个字符串上调用
    toLowercase()
    。这将为每次比较分配两个新字符串对象
  • 您正在呼叫的
    包括
    。由于某些原因,
    includes()
    方法在某些浏览器中不如
    indexOf()
    优化
用于循环(-11%)
我建议不要使用
filter()
方法,而是创建一个新的
Array
并使用
for
循环来填充它

const glossaries = this.state.glossaries;
const searchField = this.state.searchField;
const filteredWords = [];   

for (let i = 0; i < glossaries.length; i++) {
  if (glossaries[i].toLowerCase().includes(searchField.toLowerCase())) {
    filteredWords.push(glossaries[i]);
  }
}
您还可以通过在循环之前调用一次来删除searchText上的
toLowerCase()
。进行这些更改后,代码将如下所示:

const glossaries = this.state.glossaries;
const searchGlassaries = this.state.searchGlossaries;
const searchField = this.state.searchField.toLowerCase();
const filteredWords = []; 

for (let i = 0; i < glossaries.length; i++) {
  if (searchGlassaries[i].includes(searchField)) {
    filteredWords.push(glossaries[i]);
  }
}
总体而言,性能提高了70%。 我从中获得了绩效百分比

优化算法 在你的评论中,你说你想要一个优化的例子,当需求被放宽到只匹配以搜索文本开头的单词时,可以进行优化。实现这一点的一种方法是使用一个

让我们从上面的代码开始。我们先对词汇表进行排序,然后再将其存储在州中。为了对大小写进行不敏感的排序,JavaScript公开了构造函数。它提供了
compare(x,y)
方法,该方法返回:

negative value  | X is less than Y
zero            | X is equal to Y
positive value  | X is greater than Y
以及由此产生的代码:

// Static in the file
const collator = new Intl.Collator(undefined, {
  sensitivity: 'base'
});

function binarySearch(glossaries, searchText) {
  let lo = 0;
  let hi = glossaries.length - 1;

  while (lo <= hi) {
    let mid = (lo + hi) / 2 | 0;
    let comparison = collator.compare(glossaries[mid].word, searchText);

    if (comparison < 0) {
      lo = mid + 1;
    }
    else if (comparison > 0) {
      hi = mid - 1;
    }
    else {
      return mid;
    }
  }

  return -1;
}

// When you build the glossary
this.state.glossaries = ...;
this.state.glossaries.sort(function(x, y) {
  return collator.compare(x.word, y.word);
});

// When you search
const glossaries = this.state.glossaries;
const searchField = this.state.searchField.toLowerCase();
const filteredWords = [];

const idx = binarySearch(glossaries, searchField);

if (idx != -1) {
  // Find the index of the first matching word, seeing as the binary search
  // will end up somewhere in the middle
  while (idx >= 0 && collator.compare(glossaries[idx].word, searchField) < 0) {
    idx--;
  }

  // Add each matching word to the filteredWords
  while (idx < glossaries.length && collator.compare(glossaries[idx].word, searchField) == 0) {
    filteredWords.push(glossaries[idx]);
  }
}
//文件中的静态
const collator=新的Intl.collator(未定义{
敏感度:“基本”
});
函数二进制搜索(词汇表、搜索文本){
设lo=0;
设hi=glossaries.length-1;
while(lo0){
hi=mid-1;
}
否则{
中途返回;
}
}
返回-1;
}
//当您构建术语表时
this.state.glossaries=。。。;
this.state.glossaries.sort(函数(x,y){
返回collator.compare(x.word,y.word);
});
//当你搜索时
const glossaries=this.state.glossaries;
const searchField=this.state.searchField.toLowerCase();
常量filteredWords=[];
const idx=二进制搜索(词汇表,搜索字段);
如果(idx!=-1){
//查找第一个匹配单词的索引,就像二进制搜索一样
在中间的某个地方
while(idx>=0&&collator.compare(词汇表[idx].word,搜索字段)<0){
idx-;
}
//将每个匹配的单词添加到filteredWords
while(idx
此类问题适用于CodeReview,而不是StackOverflow。试着把它贴在那里。。。。此外,与常规
for
循环相比,
Array
函数(如
filter
)的速度非常慢。如果你想让你的代码更快,那就用
for
循环来重构它,这并不难。@ibrahimmahrir“原样问题”缺少很多上下文,在当前的代码评审中可能会偏离主题。更多信息请参见。@ibrahimmahrir我不同意。也许这个问题可以用更好的措辞,但这不是关于如何提高代码质量的建议。这个问题是关于一个问题:性能差。如果没有对
glossary.word
glossary
的一般描述,就很难回答这个问题。也就是说,只要你的字典被排序,二进制搜索而不是
包含
应该会产生对数时间而不是线性时间。非常感谢你。你的代码比我写的快。还有一件事,我发现了。此搜索是“searchField='he'”。它将选择“{ahello,ahellob,hello,aahello,hellob,helloc}”,但我认为如果搜索算法是“{searchField='he'}”,它会更快。它应该只给出结果“{he,hell,hellob,helloc}”,你能给我一些写这个搜索的想法吗。再次感谢您的帮助。我找到的是像这样的搜索词“A”Result“Aa,ab,ac,abbb,aee。”而不是Result“bAa,Aa,ab,Bac”。-----@user3036876检查编辑!非常感谢你,伙计。你的代码比我写的快。还有一件事,我发现了。此搜索是“searchField='he'”。它将选择“{ahello,ahellob,hello,aahello,hellob,helloc}”,但我认为如果搜索算法是“{searchField='he'}”,它会更快。它应该只给出结果“{he,hell,hellob,helloc}”,你能给我一些写这个搜索的想法吗。再次感谢您对我的帮助嗨,先生,非常感谢您的帮助。顺便问一下,你能解释一下下面的代码吗文件const collator=new Intl.collator中的Static(未定义,{sensitivity:'base'});//构建术语表时,this.state.glossaries=。。。;sort(函数(x,y){返回collator.compare(x.word,y.word);})@user3036876“文件中的静态”代码超出了类声明的范围(假设您使用的是React)。“构建术语表时”位于
this.state.glossaries
设置的位置。
const glossaries = this.state.glossaries;
const searchGlassaries = this.state.searchGlossaries;
const searchField = this.state.searchField.toLowerCase();
const filteredWords = []; 

for (let i = 0; i < glossaries.length; i++) {
  if (searchGlassaries[i].indexOf(searchField) !== -1) {
    filteredWords.push(glossaries[i]);
  }
}
negative value  | X is less than Y
zero            | X is equal to Y
positive value  | X is greater than Y
// Static in the file
const collator = new Intl.Collator(undefined, {
  sensitivity: 'base'
});

function binarySearch(glossaries, searchText) {
  let lo = 0;
  let hi = glossaries.length - 1;

  while (lo <= hi) {
    let mid = (lo + hi) / 2 | 0;
    let comparison = collator.compare(glossaries[mid].word, searchText);

    if (comparison < 0) {
      lo = mid + 1;
    }
    else if (comparison > 0) {
      hi = mid - 1;
    }
    else {
      return mid;
    }
  }

  return -1;
}

// When you build the glossary
this.state.glossaries = ...;
this.state.glossaries.sort(function(x, y) {
  return collator.compare(x.word, y.word);
});

// When you search
const glossaries = this.state.glossaries;
const searchField = this.state.searchField.toLowerCase();
const filteredWords = [];

const idx = binarySearch(glossaries, searchField);

if (idx != -1) {
  // Find the index of the first matching word, seeing as the binary search
  // will end up somewhere in the middle
  while (idx >= 0 && collator.compare(glossaries[idx].word, searchField) < 0) {
    idx--;
  }

  // Add each matching word to the filteredWords
  while (idx < glossaries.length && collator.compare(glossaries[idx].word, searchField) == 0) {
    filteredWords.push(glossaries[idx]);
  }
}