reduce map vs double for each

Benchmark created on


Setup

const users = [{ id: 1, comments: ['comment0',
'comment1',
'comment2',
'comment3',
'comment4',
'comment5',
'comment6',
'comment7',
'comment8',
'comment9',
'comment10',
'comment11',
'comment12',
'comment13',
'comment14',
'comment15',
'comment16',
'comment17',
'comment18',
'comment19',
'comment20',
'comment21',
'comment22',
'comment23',
'comment24',
'comment25',
'comment26',
'comment27',
'comment28',
'comment29',
'comment30',
'comment31',
'comment32',
'comment33',
'comment34',
'comment35',
'comment36',
'comment37',
'comment38',
'comment39',
'comment40',
'comment41',
'comment42',
'comment43',
'comment44',
'comment45']}, { id: 2, comments: ['comment0',
'comment1',
'comment2',
'comment3',
'comment4',
'comment5',
'comment6',
'comment7',
'comment8',
'comment9',
'comment10',
'comment11',
'comment12',
'comment13',
'comment14',
'comment15',
'comment16',
'comment17',
'comment18',
'comment19',
'comment20',
'comment21',
'comment22',
'comment23',
'comment24',
'comment25',
'comment26',
'comment27',
'comment28',
'comment29',
'comment30',
'comment31',
'comment32',
'comment33',
'comment34',
'comment35',
'comment36',
'comment37',
'comment38',
'comment39',
'comment40',
'comment41',
'comment42',
'comment43',
'comment44',
'comment45']}]

Test runner

Ready to run.

Testing in
TestOps/sec
forEach
const setupProblems = [];
    users.forEach(user => {
    	const { comments, ...restOfUser } = user;
        comments.forEach(comment => {
            setupProblems.push({ ...restOfUser, reason: comment });
        });
    });
    return setupProblems;
ready
reduce
return users.reduce((setupProblems, user) => {
        const { comments, ...restOfUser } = user;
        return setupProblems.concat( comments.map(comment => ({ ...restOfUser, reason: comment })))
    }, []);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.