Array Reduce Comparison

Benchmark created on


Setup

const coords = [
  [-75, -89.9],
  [32, -89.9],
  [32, -30],
  [32, -20],
  [-3, 15],
  [-3, 41],
  [-15, 41],
  [-25, 25],
  [-60, 20],
  [-60, 0],
  [-53, -19],
  [-75, -30],
  [-75, -89.9]
];


const sum = "-574.7";

const coordString = "-75,-89.9,32,-89.9,32,-30,32,-20,-3,15,-3,41,-15,41,-25,25,-60,20,-60,0,-53,-19,-75,-30,-75,-89.9"

Test runner

Ready to run.

Testing in
TestOps/sec
Array Reduce
function sumReduce(arr) {
  return arr.reduce((acc, coord) => acc + coord[0] + coord[1], 0);
}

const res1 = sumReduce(coords);

const same = `${res1}` === sum;
ready
Array Reduce (destructured)
function sumReduceDes(arr) {
  return arr.reduce((acc, [lng, lat]) => acc + lng + lat, 0);
}

const res2 = sumReduceDes(coords);

const same2 = `${res2}` === sum;
ready
For Each
function sumForEach(arr) {
  let sum = 0;
  arr.forEach(coord => {
    sum += coord[0] + coord[1];
  });
  return sum;
}

const res3 = sumForEach(coords);

const same3 = `${res3}` === sum;
ready
For-Loop
function sumForLoop(arr) {
  let sum = 0;
  for (let i = 0; i < arr.length; i++) {
    sum += arr[i][0] + arr[i][1];
  }
  return sum;
}

const res4 = sumForLoop(coords);

const same4 = `${res4}` === sum;
ready
For-Loop 2
function sumForLoop2(arr) {
  let sum = 0;
  for (let i = 0; i < arr.length; i++) {
  	const c = arr[i];
    sum += c[0] + c[1];
  }
  return sum;
}

const res5 = sumForLoop2(coords);

const same5 = `${res5}` === sum;
ready
Stringify Coords
const coordsToString = coords.toString();


const same6 = coordString === coordsToString;
ready

Revisions

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