Cache (Querying)

Benchmark created on


Description

Array approach: Pros:

  • Slightly faster if the element is earlier in the array, but this cannot be guaranteed Cons:
  • Slows down significantly the larger the cache is

Weak Set approach: Pros:

  • Approximately same speed regardless of the presence of the element in the set Cons:
  • Doesn't have fixed cache size

Setup

const myList = [];
const myListLarge = [];
const mySet = new WeakSet();
const entries = [];
let index = 0;
let indexLarge = 0;
function addToMyList(element) {
  mySet.add(element);
  if(myList.length == 20) {
  	myList[index++] = element;
  	index %= 20;
  } else {
  	myList.push(element);
  }
  if(myListLarge.length == 50) {
  	myListLarge[indexLarge++] = element;
  	indexLarge %= 20;
  } else {
  	myListLarge.push(element);
  }
}
function queryList(element) {
	return myList.includes(element);
}
function queryListLarge(element) {
	return myListLarge.includes(element);
}
function querySet(element) {
	return mySet.has(element);
}
for(let i = 0; i < 100; i++) {
	entries[i] = {
		id: i
	};
	if(i < 50) {
		addToMyList(entries[i]);
	}
}

Test runner

Ready to run.

Testing in
TestOps/sec
Array
for(let i = 0; i < 100; i++) {
	queryList(entries[i]);
}
ready
Weak Set
for(let i = 0; i < 100; i++) {
	querySet(entries[i]);
}
ready
Array (Large)
for(let i = 0; i < 100; i++) {
	queryListLarge(entries[i]);
}
ready

Revisions

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