Object Operations

by soparrissays

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/benchmark/1.0.0/benchmark.min.js"></script>
<ul id='cycleResults'>

</ul>
<div id="result">

</div>
<br>
<button id="btn">
Run Tests
</button>

JavaScript

function fill(obj, counter) {
	obj[counter.toString()] = '';
}

function makeObject(size) {
  const obj = {};
  for (let i=0; i < size; i++) {
    fill(obj, i);
  }
  return obj;
}


function getRandomInt(origMin, origMax) {
  const min = Math.ceil(origMin);
  const max = Math.floor(origMax);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

const hundred = makeObject(100);
const thousand = makeObject(1000);
const hundredThousand = makeObject(100000);
const mill = makeObject(1000000);

let hundredCounter = 99;
let thousandCounter = 999;
let hundredThousandCounter = 99999;
let millCounter = 999999;
function addHundred() {
	hundred[(++hundredCounter).toString()] = 'a';
}
function addThousand() {
	thousand[(++thousandCounter).toString()] = 'b';
}
function addHundredThousand() {
	hundredThousand[(++hundredThousandCounter).toString()] = 'c';
}
function addMil() {
	mill[(++millCounter).toString()] = 'd';
}

// I read randomly here in case we think theres some caching magic occuring
function readHundred() {
	return hundred[getRandomInt(0, 99).toString()];
}
function readThousand() {
	return thousand[getRandomInt(0, 999).toString()];
}
// Note: I use the same portions range in the thousands and millions tests because
// at some point generating a larger string from a random number causes slowness and it skews the test
function readHundredThousand() {
	return hundredThousand[getRandomInt(0, 999).toString()];
}
function readMil() {
	return mill[getRandomInt(0, 999).toString()];
}

function delhundred() {
	const key = getRandomInt(0, 99).toString();
	delete hundred[key];
  // put it back, so we don't get patchy deletes next iteration
  hundred[key] = '';
}
function delThousand() {
	const key = getRandomInt(0, 999).toString();
	delete thousand[key];
  // put it back, so we don't get patchy deletes next iteration
  thousand[key] = '';
}
function delHundredThousand() {
	const key = getRandomInt(0, 999).toString();
	delete hundredThousand[key];
  // put it back, so...