我怎样才能加快我的数组搜索功能?
How can I speed up my array search function?
我正在开发用 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()
的调用,因为您不需要在每次迭代时都调用它。
- 使用常规的旧
for
循环而不是华丽但缓慢的 Array
函数。
这是最终结果:
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]);
}
}
}
编辑:
如果要搜索 word
以 searchField
开头的词汇表,则使用 indexOf === 0
而不是 includes
作为条件,如下所示:
if(theArray[i].word.toLowerCase().indexOf(searchField) === 0) {
有多种因素导致此代码变慢:
- 您正在使用
filter()
和 lambda。这会为正在搜索的每个项目增加一个函数调用开销。
- 您在调用
includes()
之前在两个字符串上调用 toLowercase()
。这将为每次比较分配两个新的字符串对象。
- 您正在呼叫
includes
。由于某些原因,includes()
方法在某些浏览器中的优化不如 indexOf()
。
for
循环 (-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]);
}
}
toLowerCase 分配 (-45%)
由于 JavaScript 使用垃圾收集机制来释放已用内存,因此内存分配很昂贵。当执行垃圾收集时,整个程序会暂停,同时它会尝试查找不再使用的内存。
您可以通过在每次更新词汇表时复制一份词汇表来完全摆脱 toLowerCase()
(在搜索循环内),我认为这种情况并不常见。
// When you build the glossary
this.state.glossaries = ...;
this.state.searchGlossaries = this.state.glossaries.map(g => g.toLowerCase());
您还可以通过在循环之前调用一次来删除 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]);
}
}
indexOf()
而不是 includes()
(-13%)
我不太确定为什么会这样,但测试表明 indexOf
比 includes
快很多。
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]);
}
}
整体性能提高了 70%。
我从 https://jsperf.com/so-question-perf
得到了性能百分比
优化算法
在评论中您说您想要一个优化示例,可以在放宽要求以仅匹配以搜索文本开头的单词时进行优化。一种方法是 binary search.
让我们以上面的代码为起点。在将词汇表存储在状态之前,我们对词汇表进行排序。为了不区分大小写地排序,JavaScript 公开了 Intl.Collator
构造函数。它提供了 compare(x, y)
方法 returns:
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]);
}
}
我正在开发用 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());
})
}
由于问题
- 缓存对
this.state.searchField.toLowerCase()
的调用,因为您不需要在每次迭代时都调用它。 - 使用常规的旧
for
循环而不是华丽但缓慢的Array
函数。
这是最终结果:
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]);
}
}
}
编辑:
如果要搜索 word
以 searchField
开头的词汇表,则使用 indexOf === 0
而不是 includes
作为条件,如下所示:
if(theArray[i].word.toLowerCase().indexOf(searchField) === 0) {
有多种因素导致此代码变慢:
- 您正在使用
filter()
和 lambda。这会为正在搜索的每个项目增加一个函数调用开销。 - 您在调用
includes()
之前在两个字符串上调用toLowercase()
。这将为每次比较分配两个新的字符串对象。 - 您正在呼叫
includes
。由于某些原因,includes()
方法在某些浏览器中的优化不如indexOf()
。
for
循环 (-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]);
}
}
toLowerCase 分配 (-45%)
由于 JavaScript 使用垃圾收集机制来释放已用内存,因此内存分配很昂贵。当执行垃圾收集时,整个程序会暂停,同时它会尝试查找不再使用的内存。
您可以通过在每次更新词汇表时复制一份词汇表来完全摆脱 toLowerCase()
(在搜索循环内),我认为这种情况并不常见。
// When you build the glossary
this.state.glossaries = ...;
this.state.searchGlossaries = this.state.glossaries.map(g => g.toLowerCase());
您还可以通过在循环之前调用一次来删除 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]);
}
}
indexOf()
而不是 includes()
(-13%)
我不太确定为什么会这样,但测试表明 indexOf
比 includes
快很多。
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]);
}
}
整体性能提高了 70%。 我从 https://jsperf.com/so-question-perf
得到了性能百分比优化算法
在评论中您说您想要一个优化示例,可以在放宽要求以仅匹配以搜索文本开头的单词时进行优化。一种方法是 binary search.
让我们以上面的代码为起点。在将词汇表存储在状态之前,我们对词汇表进行排序。为了不区分大小写地排序,JavaScript 公开了 Intl.Collator
构造函数。它提供了 compare(x, y)
方法 returns:
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]);
}
}