Skip to content

Instantly share code, notes, and snippets.

@Joncom
Last active December 15, 2015 15:09
Show Gist options
  • Save Joncom/5279870 to your computer and use it in GitHub Desktop.
Save Joncom/5279870 to your computer and use it in GitHub Desktop.
Comparing two JavaScript methods to see which one is faster.
startTimer = function() {
var start = new Date().getTime();
return start;
};
stopTimer = function(start) {
var end = new Date().getTime();
var time = end - start;
return time;
};
functionA = function(x, y, velocity) {
var distance_x = x + 0; // replaced this.pos.x + this.size.x/2 with zero
var distance_y = y + 0; // replaced this.pos.x + this.size.x/2 with zero
var velocityX = (distance_x > 1 ? 1 : -1) * velocity * (Math.abs(distance_x) / (Math.abs(distance_x) + Math.abs(distance_y)));
var velocityY = (distance_y > 1 ? 1 : -1) * velocity * (Math.abs(distance_y) / (Math.abs(distance_x) + Math.abs(distance_y)));
return {
x: velocityX,
y: velocityY
};
};
functionB = function(x, y, velocity) {
var centerX = 0; // replaced this.pos.x + this.size.x/2 with zero
var centerY = 0; // replaced this.pos.x + this.size.x/2 with zero
var angleToTarget = Math.atan2(y - centerY, x - centerX);
var velocityX = Math.cos(angleToTarget) * velocity;
var velocityY = Math.sin(angleToTarget) * velocity;
return {
x: velocityX,
y: velocityY
};
};
var total_time_a = 0;
var total_time_b = 0;
var start, end, time, x, y, velocity, result;
for (var i = 0; i < 1000000; i++) {
// Generate random x, y, and velocity values.
x = Math.floor(Math.random() * 100000);
y = Math.floor(Math.random() * 100000);
velocity = Math.floor(Math.random() * 100000);
// Time method A.
start = startTimer();
result = functionA(x, y, velocity);
time = stopTimer(start);
total_time_a += time;
// Time method B.
start = startTimer();
result = functionB(x, y, velocity);
time = stopTimer(start);
total_time_b += time;
}
var winner = (total_time_a < total_time_b ? 'Method A' : 'Method B');
var speed_factor = Math.max(total_time_a, total_time_b) / Math.min(total_time_b, total_time_a);
var text = 'Winner: ' + winner + "\n" + 'It was ' + speed_factor.toFixed(2) + ' times faster.';
document.write('DONE! ');
document.write(text);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment