# Distance Performance (v2)

## Setup

function distance1(_a, _b) {

const a_x = _a.x
const a_y = _a.y
const b_x = _b.x
const b_y = _b.y

const a_w2 = _a.width / 2
const a_h = _a.height
const b_w2 = _b.width / 2
const b_h = _b.height;

let min = 99999999
for(const a_c of [{ x: a_x + a_w2, y: a_y - a_h},
{ x: a_x + a_w2, y: a_y},
{ x: a_x - a_w2, y: a_y - a_h},
{ x: a_x - a_w2, y: a_y}]) {
for(const b_c of [{ x: b_x + b_w2, y: b_y - b_h},
{ x: b_x + b_w2, y: b_y},
{ x: b_x - b_w2, y: b_y - b_h},
{ x: b_x - b_w2, y: b_y}]) {
const d = Math.hypot(a_c.x - b_c.x, a_c.y - b_c.y)
if(d < min) min = d
}
}
return min
}

function distance2(_a, _b, in_check) {
const a_x = _a.x
const a_y = _a.y
const b_x = _b.x
const b_y = _b.y

const a_w2 = _a.width / 2
const a_h = _a.height
const b_w2 = _b.width / 2
const b_h = _b.height

let min = 99999999;
let a_x1 = a_x + a_w2;
let a_x2 = a_x - a_w2;
let b_x1 = b_x + b_w2;
let b_x2 = b_x - b_w2;
let a_y1 = a_y;
let a_y2 = a_y - a_h;
let b_y1 = b_y;
let b_y2 = b_y - b_h;
let minX = Math.min(
Math.abs(a_x1 - b_x1),
Math.abs(a_x1 - b_x2),
Math.abs(a_x2 - b_x1),
Math.abs(a_x2 - b_x2)
);
let minY = Math.min(
Math.abs(a_y1 - b_y1),
Math.abs(a_y1 - b_y2),
Math.abs(a_y2 - b_y1),
Math.abs(a_y2 - b_y2)
);
return Math.hypot(minX, minY);
}
var CASES = new Array(100).fill(undefined).map(() => {
return [
{
x: Math.random() * 100,
y: Math.random() * 100,
width: Math.random() * 10,
height: Math.random() * 10
},
{
x: Math.random() * 100,
y: Math.random() * 100,
width: Math.random() * 10,
height: Math.random() * 10
}
];
});
var TOTAL1 = 0;
var TOTAL2 = 0;

## Test runner

Testing in
TestOps/sec
Old Test
for(let i = 0; i < CASES.length; i++) {
TOTAL1 += distance1(CASES[i][0], CASES[i][1]);
}
New Test
for(let i = 0; i < CASES.length; i++) {
TOTAL2 += distance2(CASES[i][0], CASES[i][1]);
}