forEach vs reduce

Benchmark created on


Setup

const maxLength = 10000; // Example length
const a = {
    gamePlayers: Array.from({ length: maxLength }).reduce((acc, _, i) => {
        acc[i + 1] = Array.from({ length: 6 }, (_, j) => j % (i + 1) === 0 ? 1 : 0);
        return acc;
    }, {}),
};

Test runner

Ready to run.

Testing in
TestOps/sec
forEach
Object.entries(a.gamePlayers).forEach(([playerID, bets]) => {
    bets.forEach((bet, index) => {
        if (bet <= 0) return;
        result1[index].push(playerID);
    });
});
ready
reduce
const result2 = Object.entries(a.gamePlayers).reduce((acc, [playerID, playerBet]) => {
    playerBet.reduce((acc, betAmount, index) => {
        if (betAmount <= 0) return acc;
        acc[index].push(playerID);
        return acc;
    }, acc);
    return acc;
}, Array.from({ length: 6 }, () => []));
ready

Revisions

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