reduce vs loop

Benchmark created on


Setup

let cards = [];
const N = 1_000_000

for (let i = 0; i < N; i++) {
	cards.push({ value: parseInt(Math.random() * 10 + 1) })
}

Test runner

Ready to run.

Testing in
TestOps/sec
kifla
  const totalValue = cards.reduce((sum, card) => sum + card.value, 0);
  const numberOfAces = cards.filter(card => card.value === 11).length;

  let adjustedValue = totalValue;

  // Adjust the total value if there are aces and the total value exceeds 21
  while (adjustedValue > 21 && numberOfAces > 0) {
    adjustedValue -= 10;
    numberOfAces--;
 }
ready
jovan
  let sum = 0;
  let aces = 0;
  for (const card of cards) {
    sum += card.value;
    aces += card.value == 11;
  }

  while (aces > 0 && sum > 21) {
    sum -= 10;
  }
ready

Revisions

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