squaredDistance

Benchmark created on


Setup

const squaredDistanceCache = new Map();
const squaredDistanceObject = {};

Test runner

Ready to run.

Testing in
TestOps/sec
map
function squaredDistance(vector1, vector2) {
	const dx = Math.abs(vector2.x - vector1.x);
	const dy = Math.abs(vector2.y - vector1.y);

	let cacheDX = squaredDistanceCache.get(dx);
	if (!cacheDX) {
		cacheDX = new Map();
		squaredDistanceCache.set(dx, cacheDX);
	}

	let result = cacheDX.get(dy);
	if (result) {
		return result;
	}

	result = dx * dx + dy * dy;

	cacheDX.set(dy, result);

	return result;
}

for (let x = 0; x < 512; x++) {
	for (let y = 0; y < 512; y++) {
		const calculated = squaredDistance(x, y);
		const calculated2 = squaredDistance(x, y);
		const calculated3 = squaredDistance(x, y);
	}
}
ready
object
function squaredDistance(vector1, vector2) {
	const dx = Math.abs(vector2.x - vector1.x);
	const dy = Math.abs(vector2.y - vector1.y);

	let cacheDX = squaredDistanceObject[dx];
	if (!cacheDX) {
		cacheDX = squaredDistanceObject[dx] = {};
	}

	let result = cacheDX[dy];
	if (result) {
		return result;
	}

	result = dx * dx + dy * dy;

	cacheDX[dy] = result;

	return result;
}

for (let x = -512; x < 512; x++) {
	for (let y = -512; y < 512; y++) {
		const calculated = squaredDistance(x, y);
		const calculated2 = squaredDistance(x, y);
		const calculated3 = squaredDistance(x, y);
	}
}
ready
no cache
function squaredDistance(vector1, vector2) {
	const dx = vector2.x - vector1.x;
	const dy = vector2.y - vector1.y;
	return dx * dx + dy * dy;
}

for (let x = -512; x < 512; x++) {
	for (let y = -512; y < 512; y++) {
		const calculated = squaredDistance(x, y);
		const calculated2 = squaredDistance(x, y);
		const calculated3 = squaredDistance(x, y);
	}
}
ready
object with ??=
function squaredDistance(vector1, vector2) {
	const dx = Math.abs(vector2.x - vector1.x);
	const dy = Math.abs(vector2.y - vector1.y);
	return (squaredDistanceObject[dx] ??= {})[dy] ??= (dx * dx + dy * dy);
}

for (let x = -512; x < 512; x++) {
	for (let y = -512; y < 512; y++) {
		const calculated = squaredDistance(x, y);
		const calculated2 = squaredDistance(x, y);
		const calculated3 = squaredDistance(x, y);
	}
}
ready

Revisions

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