Cache (Adding)

Benchmark created on


Description

Array approaches: Pros:

  • Faster Cons:
  • Requires manual tracking of array size and may leak memory if implemented improperly

WeakSet approach: Pros:

  • Automatically manages memory and size for you Cons:
  • Slower

Test runner

Ready to run.

Testing in
TestOps/sec
Array Push + Shift
const myList = [];
const entries = [];
function addToMyList(element) {
  myList.push(element);
  if(myList.length > 20) {
    myList.shift();
  }
}
for(let i = 0; i < 100; i++) {
	addToMyList(entries[i] = {
		id: i
	});
}
ready
Array Unshift + Pop
const myList = [];
const entries = [];
function addToMyList(element) {
  myList.unshift(element);
  if(myList.length > 20) {
    myList.pop();
  }
}
for(let i = 0; i < 100; i++) {
	addToMyList(entries[i] = {
		id: i
	});
}
ready
Array Rolling
const myList = [];
const entries = [];
let index = 0;
function addToMyList(element) {
  if(myList.length == 20) {
  	myList[index++] = element;
  	index %= 20;
  } else {
  	myList.push(element);
  }
}
for(let i = 0; i < 100; i++) {
	addToMyList(entries[i] = {
		id: i
	});
}
ready
Weak Set
const mySet = new WeakSet();
const entries = [];
function addToMyList(element) {
	mySet.add(element);
}
for(let i = 0; i < 100; i++) {
	addToMyList(entries[i] = {
		id: i
	});
}
ready

Revisions

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