Seems like Math.floor(x)
is slower than (int) x
as suggested in this test:
public final class FloorRunningTime {
public static void main(final String[] args) {
final double number = 4999.7;
floorMethod(number);
downcastMethod(number);
}
private static void floorMethod(final double number) {
long start = System.nanoTime();
final int floorValue = (int) Math.floor(number);
long duration = System.nanoTime() - start;
System.out.printf("Floor value is: %d. Running time (nanoseconds): %d.%n", floorValue,
duration);
}
private static void downcastMethod(final double number) {
long start = System.nanoTime();
final int floorValue = (int) number;
long duration = System.nanoTime() - start;
System.out.printf("Floor value is: %d. Running time (nanoseconds): %d.%n", floorValue,
duration);
}
}
The output for this run is:
Floor value is: 4999. Running time (nanoseconds): 807820.
Floor value is: 4999. Running time (nanoseconds): 236.
This might make a difference on when running repetitive calls in order to floor different numbers.
Is any reason one should use Math.floor(x)
instead of (int) x
, when doing the operation for positive numbers?