我需要遍历大量记录并计算特定字段中不同值的数量:
>> const cats = [
{name: 'Sophie', color: 'black'},
{name: 'Moo', color: 'grey'},
{name: 'Tipper', color: 'black'}
]
>> countBy(cats, 'color')
Map('black' => 2, 'grey' => 1) # (precise data structure unimportant)
嘿,这就是 lodash countBy 的用途!但在我的应用程序中,性能是最重要的。在我的(非常非正式的)基准测试中,这个简单的代码比 lodash 高出大约 50%:
function countBy<R extends object>(records: R[], key: keyof R) {
const counts = new Map<keyof R, number>()
for (const i = 0; i < records.length; i++) {
const value = records[i][key]
counts.set(value, (counts.get(value) || 0) + 1)
}
}
(这也许不足为奇,因为它不需要处理比
keyof R
更高级的“iteratees”。)
问题:有没有办法在速度方面击败这个算法?