Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Distance calculation
// "noop" baseline to compare against
start = performance.now();
for (x = 0; x < 1000; x++) {
for (y = 0; y < 1000; y++) {
}
}
finish = performance.now();
console.debug("Baseline: " + (finish - start) + "ms");
// Math.sqrt and Math.pow
start = performance.now();
for (x = 0; x < 1000; x++) {
for (y = 0; y < 1000; y++) {
Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
}
}
finish = performance.now();
console.debug("Math.sqrt & Math.pow: " + (finish - start) + "ms");
// Math.sqrt and manual squaring
start = performance.now();
for (x = 0; x < 1000; x++) {
for (y = 0; y < 1000; y++) {
Math.sqrt(x*x + y*y);
}
}
finish = performance.now();
console.debug("Math.sqrt & manual squaring: " + (finish - start) + "ms");
// Math.hypot
start = performance.now();
for (x = 0; x < 1000; x++) {
for (y = 0; y < 1000; y++) {
Math.hypot(x, y);
}
}
finish = performance.now();
console.debug("Math.hypot: " + (finish - start) + "ms");
// without sqrt (not necessary for when comparing distances))
start = performance.now();
for (x = 0; x < 1000; x++) {
for (y = 0; y < 1000; y++) {
x*x + y*y;
}
}
finish = performance.now();
console.debug("Manual squaring and addition: " + (finish - start) + "ms");
// index hypot results and using index
start = performance.now();
t = [];
for (x = 0; x < 1000; x++) {
t[x] = [];
for (y = 0; y < 1000; y++) {
t[x][y] = Math.hypot(x, y);
}
}
finish = performance.now();
console.debug("Indexed hypot generation: " + (finish - start) + "ms");
start = performance.now();
for (x = 0; x < 1000; x++) {
for (y = 0; y < 1000; y++) {
t[x][y];
}
}
finish = performance.now();
console.debug("Using indexed hypot: " + (finish - start) + "ms");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.