foreach vs filter+map
Date tested:
5 years ago
User agent:
Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.81 Safari/537.36
Test name
Executions per second
filter + map
604010.9 Ops/sec
forEach
719407.8 Ops/sec
Benchmark definition (click to collapse):
Script Preparation code:
var contacts = { 'a1@a.com': {id: 1}, 'a2@a.com': {id: 2}, 'a3@a.com': {id: 3}, 'a4@a.com': {id: 4}, 'a5@a.com': {id: 5}, 'a6@a.com': {id: 6}, 'a7@a.com': {id: 7}, 'a8@a.com': {id: 8}, 'a9@a.com': {id: 9}, 'a10@a.com': {id: 10}, } var selectedItems = [1,3,7];
Tests:
filter + map
selectedItems = Object.values(contacts).filter(contact => selectedItems.indexOf(contact.id) === -1).map(contact => contact.id)
forEach
Object.values(contacts).forEach((contact) => { if (selectedItems.indexOf(contact.id) === -1) { selectedItems.push(contact.id); } });
Open this result on MeasureThat.net