Skip to content

Instantly share code, notes, and snippets.

@laszlokorte
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save laszlokorte/2ee2972cf280e7988d25 to your computer and use it in GitHub Desktop.
Save laszlokorte/2ee2972cf280e7988d25 to your computer and use it in GitHub Desktop.
// Only scalar values, both for parameters and return values.
// Calculation must be split into 2 methods. Ugly code, duplicate calculations.
public final class VectorMath {
public static double getRotatedX(final double x, final double y,
final double angle) {
return x * Math.cos(angle) - y * Math.sin(angle);
}
public static double getRotatedY(final double x, final double y,
final double angle) {
return y * Math.cos(angle) + x * Math.sin(angle);
}
}
// Scalar values as parameters. Object as return value.
// nicer code, no duplicate calculations
// But an extra allocation. Can java optimize this away?
public final class VectorMath2 {
public static Vec2 getRotated(final double x, final double y,
final double angle) {
double cos = Math.cos(angle);
double sin = Math.sin(angle);
return new Vec2(x * cos - y * sin, y * cos + x * sin);
}
}
// Scalar values for both parameters and return value.
// Even nicer code, no duplicate calculations.
// But the caller needs to allocate an Vector object and another one is allocated for the return value.
// Can java optimize those allocations away?
public final class VectorMath {
public static Vec2 getRotated(Vec2 p,
final double angle) {
double cos = Math.cos(angle);
double sin = Math.sin(angle);
return new Vec2(p.x * cos - p.y * sin, p.y * cos + p.x * sin);
}
}
// Object as parameter, but no return value.
// Instead a second parameter in which the result is written.
// The caller can preallocate 2 Vec2 objects on startup. No allocations in the loop are needed.
// Code is a bit ugly because a parameter is used for the return value.
public final class VectorMath {
public static void getRotatedInto(Vec2 p,
final double angle, Vec2 target) {
double cos = Math.cos(angle);
double sin = Math.sin(angle);
target.x = p.x * cos - p.y * sin;
target.y = p.y * cos + p.x * sin;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment