unique-objects-array

JavaScript performance comparison

Test case created by jorgecasar

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  const items_unique = [];
  const items = [];
  const names = ['one', 'two', 'three', 'four', 'five'];
  for (var i = 0; i < 1000; i++) {
      items_unique.push({ name: 'name_' + i });
      items.push({ name: names[i%5] });
  }
  

};
</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
Reducer
function snippet(arr) {
  return arr.reduce((acc,cur) => {
    if(!acc[cur.name]) {
      acc.set(cur.name, cur);
    }
    return acc;
  }, new Map());
}

snippet(items);
snippet(items_unique);
pending…
Map
function snippet(arr) {
  return new Map(arr.map((item) => [item.name, item]));
}

snippet(items);
snippet(items_unique);
pending…
For
function snippet(arr) {
  const uniqueValues = new Map();
  for(let i = 0, len = arr.length; i < len; i+=1) {
    if(!uniqueValues.has(arr[i].name)) {
      uniqueValues.set(arr[i].name, arr[i]);
    }
  }
  return uniqueValues;
}

snippet(items);
snippet(items_unique);
pending…
Foreach
function snippet(arr) {
  const uniqueValues = new Map();
  arr.forEach(item => {
    if(!uniqueValues.has(item.name)) {
      uniqueValues.set(item.name, item);
    }
  });
  return uniqueValues;
}

snippet(items);
snippet(items_unique);
pending…
Doble for
function snippet(arr) {
  const uniqueValues = new Map();
  const obj = {};
  for(let i = 0, len = arr.length; i < len; i+=1) {
    if(!obj[arr[i].name]) {
       obj[arr[i].name] = true;
    }
  }
  for(let i in obj) {
    uniqueValues.set(obj[i].name, obj[i]);
  }
  return uniqueValues;
}

snippet(items);
snippet(items_unique);
pending…

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

Compare results of other browsers

0 Comments