Using a throw is faster than using a floor or round. I suspect casting is more optimized by the HotSpot compiler.
public class Main { public static final int ITERS = 1000 * 1000; public static void main(String... args) { for (int i = 0; i < 3; i++) { perfRoundTo3(); perfCastRoundTo3(); } } private static double perfRoundTo3() { double sum = 0.0; long start = 0; for (int i = -20000; i < ITERS; i++) { if (i == 0) start = System.nanoTime(); sum += roundTo3(i * 1e-4); } long time = System.nanoTime() - start; System.out.printf("Took %,d ns per round%n", time / ITERS); return sum; } private static double perfCastRoundTo3() { double sum = 0.0; long start = 0; for (int i = -20000; i < ITERS; i++) { if (i == 0) start = System.nanoTime(); sum += castRoundTo3(i * 1e-4); } long time = System.nanoTime() - start; System.out.printf("Took %,d ns per cast round%n", time / ITERS); return sum; } public static double roundTo3(double d) { return Math.round(d * 1000 + 0.5) / 1000.0; } public static double castRoundTo3(double d) { return (long) (d * 1000 + 0.5) / 1000.0; } }
prints
Took 22 ns per round Took 9 ns per cast round Took 23 ns per round Took 6 ns per cast round Took 20 ns per round Took 6 ns per cast round
Note: as of Java 7, the floor (x + 0.5) and round (x) are not doing the same thing as in this issue. Why Math.round (0.4999999999999999994) returns 1
This will correctly round up to a presentation error. This means that although the result is not accurate, a decimal number, for example. 0.001 doesn't seem to be accurate when you use toString (), it will fix it. Its only when you convert to BigDecimal or perform an arithmetic operation, you will see this view error.
Peter Lawrey
source share