Calling Math.floor() simply takes too long. The problem with optimizing is that you can’t simply cast the floatingpoint number to an integer, because that will result in invalid results for negative numbers. If we know our input values are in a specific range, we can safely add a certain (big) constant to the input, cast the guaranteed positive value to an integer and subtract the constant again.
The code is ~9x faster than Math.floor(). Replacing the doubles with floats makes it faster, but the results are rather… random, so don’t.
public class FastMath
{
private static final int BIG_ENOUGH_INT = 16 * 1024;
private static final double BIG_ENOUGH_FLOOR = BIG_ENOUGH_INT;
private static final double BIG_ENOUGH_ROUND = BIG_ENOUGH_INT + 0.5;
public static int fastFloor(float x) {
return (int) (x + BIG_ENOUGH_FLOOR) - BIG_ENOUGH_INT;
}
public static int fastRound(float x) {
return (int) (x + BIG_ENOUGH_ROUND) - BIG_ENOUGH_INT;
}
public static int fastCeil(float x) {
return BIG_ENOUGH_INT - (int)(BIG_ENOUGH_FLOOR-x); // credit: roquen
}
}