Type Guard "Switch" vs Map

Benchmark created on


Setup

function isX(thing) {
	return thing.type === 'x';
}

function doX(thing) {
	return thing.value + 1;
}

function isY(thing) {
	return thing.type === 'y';
}

function doY(thing) {
	return thing.value + 'hello';
}

function isZ(thing) {
	return thing.type === 'z';
}

function doZ(thing) {
	return !thing.value;
}

const lookup = new Map([
  ['x', (thing) => {
  	if (isX(thing)) {
  		return doX(thing);
  	}
  	throw 'NOT X';
  }],
  ['y', (thing) => {
  	if (isY(thing)) {
  		return doY(thing);
  	}
  	throw 'NOT Y';
  }],
  ['z', (thing) => {
  	if (isZthing)) {
  		return doZ(thing);
  	}
  	throw 'NOT Z';
  }]
]);

// populates either number, string or boolean
const things = [];
for (let i = 0; i < 100000; i++) {
	const rand = Math.random();
	if (rand <= 0.333) {
		things.push({
			type: 'x',
			value: Math.random()
		});
	} else if (rand <= 0.666) {
		things.push({
			type: 'y',
			value: Math.random().toString()
		});
	} else {
		things.push({
			type: 'z',
			value: Math.random() > 0.5
		});
	}
}

Test runner

Ready to run.

Testing in
TestOps/sec
Type Guard "Switch"
for (const thing of things) {
	if (isX(thing)) {
		doX(thing);
	} else if (isY(thing)) {
		doY(thing);
	} else if (isZ(thing)) {
		doZ(thing);
	}
}
ready
Map
for (const thing of things) {
	const runner = lookup.get(thing.type);
	if (runner) {
		runner(thing);
	} else {
		throw 'NO TYPE FOUND'
	}
}
ready

Revisions

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