Find by ID Benchmark.js

by Santiago J

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/benchmark/2.1.1/benchmark.min.js"></script>

JavaScript

const suite = new Benchmark.Suite;

const size = 20;
const searchFor = [.01, .25, .50, .75, .99].map(s => Math.floor(s*size));

function ArrItem(id, data) {
	this.id = id;
  this.data = data;
}

const arr = [];
const map = new Map();
const obj = {};

for (let i = 0; i < size; i++) {
	arr.push(new ArrItem(i, i));
  map.set(i, i);
  obj[i] = i;
}

function scan(arr, x) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].id === x) return arr[i].data;
  }
}

//* add tests
suite
.add('scan items', function() {
	for (const x of searchFor) {
  	scan(arr, x);
  }
})
.add('map index', function() {
	for (const x of searchFor) {
  	return map.get(x);
  }
})
.add('obj index', function() {
	for (const x of searchFor) {
  	return obj[x];
  }
})
.on('cycle', function(event) {
  console.log(String(event.target));
})
.on('complete', function() {
  console.log('Fastest is ' + this.filter('fastest').map('name'));
})
.run({ 'async': true });
//*/