为什么组合.map和.filter比两个for循环执行得更快?



做Hackerrank挑战,寻找比我目前的问题更快的解决方案。我对。map和。filter的理解是它们都是O(n)函数。但是在执行时使用filter和map比两个for循环要快得多。为什么呢?

供参考:我的两个for循环实现:

function matchingStrings(strings, queries) {
let countArr = new Array(queries.length).fill(0);
let index = 0;
for(const queryStr of queries){
for(const findStr of strings){
if(queryStr === findStr){
countArr[index] += 1;
}
}
index++;
}
return countArr;
}

更快的过滤器和映射实现(来自https://gist.github.com/rahul4coding/64023e39017f0a5915a9ff884d18446d)

function matchingStrings(strings, queries) {
return queries.map(x=>strings.filter(y=>y===x).length)
}

如果没有数据集,复制这个问题有点困难,但是我已经创建了一个测试程序来运行这两个函数,似乎没有太大的区别。有时嵌套的for循环更快。

const queriesT = ["foo0", "foo1", "foo2", "foo3", "foo4", "foo5",
"foo6", "foo7", "foo8", "foo9", "foo10", "foo11", "foo12",
"foo13", "foo14", "foo15", "foo16", "foo17", "foo18", "foo19",];
const testStrs = [ "foo1", "foo1", "foo5", "foo19", "foo14", "foo2", "foo15", "foo19",
"foo2", "foo10", "foo18", "foo16", "foo14", "foo2", "foo15", "foo19",
"foo5", "foo12", "foo6", "foo17", "foo14", "foo2", "foo15", "foo19",
"foo1", "foo9", "foo10", "foo7", "foo14", "foo2", "foo15", "foo19"];
function matchingStrings() {
let countArr = new Array(queriesT.length).fill(0);
let index = 0;
for(const queryStr of queriesT){
for(const findStr of testStrs){
if(queryStr === findStr){
countArr[index] += 1;
}
}
index++;
}
return countArr;
}
function matchingStrings2(strings, queries) {

return queriesT.map(x=>testStrs.filter(y=>y===x).length);
}
function testFunc(func){

const ms = new Date().getTime();

const r = func();

console.log("result: " + r);

const msA = new Date().getTime();

console.log("Time (ms): " + (msA - ms));

}
testFunc(matchingStrings);
testFunc(matchingStrings2);

最新更新