为了提高性能,您需要测量哪种解决方案更快。让我们玩一会儿
https://jsperf.com/filter-than-map-or-reduce/1
欢迎任何其他测试案例。
![enter image description here](https://istack.dev59.com/6JQgv.webp)
如果您想对比 NodeJS 性能(请记得安装 npm i benchmark
)
var suite = new (require('benchmark')).Suite
function getSampleInput() {
return [{file: 'foo'}, {other: 'bar'}, {file: 'baz'}, {file: 'quux'}, {other: 'quuxdoo'}, {file: 'foobar'}, {file: 'foo'}, {other: 'bar'}, {file: 'baz'}, {file: 'quux'}, {other: 'quuxdoo'}, {file: 'foobar'}, {file: 'foo'}, {other: 'bar'}, {file: 'baz'}, {file: 'quux'}, {other: 'quuxdoo'}, {file: 'foobar'}, {file: 'foo'}, {other: 'bar'}, {file: 'baz'}, {file: 'quux'}, {other: 'quuxdoo'}, {file: 'foobar'}, {file: 'foo'}, {other: 'bar'}, {file: 'baz'}, {file: 'quux'}, {other: 'quuxdoo'}, {file: 'foobar'}, {file: 'foo'}, {other: 'bar'}, {file: 'baz'}, {file: 'quux'}, {other: 'quuxdoo'}, {file: 'foobar'}, {file: 'foo'}, {other: 'bar'}, {file: 'baz'}, {file: 'quux'}, {other: 'quuxdoo'}, {file: 'foobar'}, {file: 'foo'}, {other: 'bar'}, {file: 'baz'}, {file: 'quux'}, {other: 'quuxdoo'}, {file: 'foobar'}]
}
function reduce(results) {
return results.reduce(
(acc, result) => result.file ? acc.concat([result.file]) : acc ,
[]
)
}
function filterThanMap(results) {
return results.filter(function(r){
return r.file;
})
.map(function(r){
return r.file;
});
}
function forEach(results) {
const files = [];
results.forEach(function(r){
if(r.file) files.push(r.file);
});
return files
}
suite
.add('filterThanMap', function() {filterThanMap(getSampleInput())})
.add('reduce', function() {reduce(getSampleInput())})
.add('forEach', function() {forEach(getSampleInput())})
.on('complete', function() {
console.log('results:')
this.forEach(function(result) {
console.log(result.name, result.count, result.times.elapsed)
})
console.log('the fastest is', this.filter('fastest').map('name')[0])
})
.run()
results
是什么?一个多维数组[{file:{file:1}}, {notfile:{file:1}}]
? - guest271314[{},{file:x}, {}, {file:y}]
,等等。 - Alexander Mills[{},{file:x}, {}, {file:y}]
。嗯,这个数组与 JavaScript 中的上下文不匹配。在这种情况下,.map()
不是必需的。您可以仅使用.filter()
来返回预期的结果。 - guest271314results
解释为嵌套数组。为什么需要.map()
?返回一个[x,y]
数组?期望的结果是什么? - guest271314Array.prototype
方法的要求是什么? - guest271314