Repeated TypeOf Checks

Benchmark created on


Setup

const options = [{}, 123, "hello"];

Test runner

Ready to run.

Testing in
TestOps/sec
Repeated typeof/if
let randomIndex = Math.floor(Math.random() * options.length);
let randomValue = options[randomIndex];

if (typeof randomValue === 'string') {
	result = 'string';
} else if (typeof randomValue === 'number') {
	result = 'number';
} else if (typeof randomValue === 'object') {
	result = 'object';
}
ready
Caching
let randomIndex = Math.floor(Math.random() * options.length);
let randomValue = options[randomIndex];

const typeOfRandomValue = typeof randomValue;
if (typeOfRandomValue === 'string') {
	result = 'string';
} else if (typeOfRandomValue === 'number') {
	result = 'number';
} else if (typeOfRandomValue === 'object') {
	result = 'object';
}
ready
Repeated typeof/switch
let randomIndex = Math.floor(Math.random() * options.length);
let randomValue = options[randomIndex];

const typeOfRandomValue = typeof randomValue;
switch (typeOfRandomValue) {
	case 'string':
		result = 'string';
		break;
	case 'number':
		result = 'number';
		break;
	case 'object':
		result = 'object';
		break;
}
ready

Revisions

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