uniq by prop

JavaScript performance comparison

Test case created by mister-what

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  const createObjWithId = (pDuplicate = 0.5) => (item, index, array)=> ({
    someProp: "value",
    id: Math.round(
      Math.random() * array.length * pDuplicate
    ).toString(36)
  });
  const testArray = new Array(500).fill(null).map(createObjWithId(0.5));
  
  const uniqByProp_classic = prop => arr =>
    Object.values(
      arr.reduce(
        (acc, item) =>
          item && item[prop]
            ? { ...acc, [item[prop]]: item } // just include items with the prop
            : acc,
        {}
      )
    );
  
  const uniqByProp_mutation = prop => arr =>
    Object.values(
      arr.reduce(
        (acc, item) => (
          item && item[prop] && (acc[item[prop]] = item), acc
        ), // using object mutation (faster)
        {}
      )
    );
  
  const uniqByProp_map = prop => arr =>
    Array.from(
      arr
        .reduce(
          (acc, item) => (
            item && item[prop] && acc.set(item[prop], item),
            acc
          ), // using map (preserves ordering)
          new Map()
        )
        .values()
    );
  
  const classicId = uniqByProp_classic("id");
  const mutationId = uniqByProp_mutation("id");
  const mapId = uniqByProp_map("id");
  

};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
classic
classicId(testArray)
pending…
mutation
mutationId(testArray)
pending…
map
mapId(testArray)
pending…

Compare results of other browsers

Revisions

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

0 Comments