Manual For Loop - Fixed

Benchmark created on


Setup

const keys = ["hello", "world", "wow", "this", "is", "fun"];

const values = [];
for (let i = 0; i < 100_000; i++) {
  values.push([keys[Math.floor(Math.random() * keys.length)], i]);
}

function groupByFor(iter, fn) {
  const result = {};
  for (const value of iter) {
    const entry = (result[fn(value)] ||= []);
    entry.push(value);
  }
  return result;
}

function groupByReduce(iter, fn) {
  return iter.reduce((result, value) => {
    const entry = (result[fn(value)] ||= []);
    entry.push(value);
    return result;
  }, {});
}

Test runner

Ready to run.

Testing in
TestOps/sec
reduce
groupByReduce(values,(arg)=>arg[0])
ready
for loop
groupByFor(values,(arg)=>arg[0])
ready

Revisions

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