Reduce vs for (v4)

Revision 4 of this benchmark created on


Setup

const size = 10000000;

function getArrayValueDifferenceReduce(a, b) {
  let diff = 0;

  if (a.length === b.length) {
    return diff;
  }

  return (
    b.reduce((acc, curr) => acc + curr, 0) -
    a.reduce((acc, curr) => acc + curr, 0)
  );
}

function getArrayValueDifferenceReduceOptim(a, b) {
	function sum(a, b) {
		return a + b;
	}
	
  let diff = 0;

  if (a.length === b.length) {
    return diff;
  }

  return (
    b.reduce(sum, 0) -
    a.reduce(sum, 0)
  );
}

function getArrayValueDifferenceLoop(a, b) {
  let diff = 0;
  if (a.length === b.length) {
    return diff;
  }
  for (let i = 0; i < b.length; i++) {
    diff += b[i];
  }
  for (let i = 0; i < a.length; i++) {
    diff -= a[i];
  }
  return diff;
}

Test runner

Ready to run.

Testing in
TestOps/sec
reduce
const newValue = 1;
const a = Array.from({ length: size }, (_, i) => i);
const b = [...a, newValue];
const result = getArrayValueDifferenceReduce(a, b)
ready
reduce optim
const newValue = 1;
const a = Array.from({ length: size }, (_, i) => i);
const b = [...a, newValue];
const result = getArrayValueDifferenceReduceOptim(a, b)
ready
loop
const newValue = 1;
const a = Array.from({ length: size }, (_, i) => i);
const b = [...a, newValue];
const result = getArrayValueDifferenceLoop(a, b)
ready

Revisions

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