我有一个由几个单词组成的数组,我正在找到一个特定的单词。下面是我目前的解决方案,对于小型数组来说,它的工作非常好。但是如果这个数组包含10,000个单词,那么我的解决方案将需要大量的内存和CPU资源,因为它不够高效。如何使我的代码在性能上更好,并在JavaScript?中为大型数组占用更少的资源。
var words = ['apple', 'orange', 'ananas', 'banana', 'mango', 'lemon', 'tomato'];
function search (term) {
for (var i = 0, len = words.length; i < len; i++) {
if (words[i] === term) {
console.log(words[i] + ' is found at ' + i);
}
}
}
search('tomato');
发布于 2014-12-18 07:41:42
用单词作为键预先填充字典(对象)。那么查找仅仅是dict[term]
。
var words = ['apple', 'orange', 'ananas', 'banana', 'mango', 'lemon', 'tomato'];
var dict = {};
function prepopulate() {
words.forEach(function(word, i) { dict[word] = i; });
}
function search (term) {
if (term in dict) {
console.log(term + ' is found at ' + dict[term]);
}
}
prepopulate();
search('tomato');
发布于 2014-12-18 07:36:24
嗯,我不知道我是不是错过了什么,但为什么你不能用indexOf
function search (term) {
console.log(term + " is found at " + words.indexOf(term));
}
发布于 2014-12-18 07:48:18
好吧,大家一致的答案是,迭代数组最快的方法是循环,您使用了,所以做得很好。但是,我为这个特殊情况创建了一个jsPerf,而且..。
事实证明,while
循环更快!事实上,整个过程似乎快了90%。不知道为什么会这样,但证据已经全部存在(至少在我的浏览器中是这样)。当然,我假设如果数组中有多个值实例,那么您将希望知道匹配它的所有索引,而不仅仅是第一次出现,因此返回值也是一个数组。无论如何,这里是获胜的代码块:
//Note that I have 2 instances of tomato!
var words = ['apple', 'orange', 'tomato', 'ananas', 'banana', 'mango', 'lemon', 'tomato'];
//Gave the function two arguments to make it more generic
function search (arr, term) {
var i, indices = [];
while (i < arr.length) {
if (arr[i] === term) {
indices.push(i);
}
i++;
}
return indices;
}
search(words, 'tomato');
https://stackoverflow.com/questions/27541311
复制相似问题