public class Main { public static void main(String[] args) throws InterruptedException { for (int i = 0; i < 10; i++) { measurementIteration(); } } public static void measurementIteration() { long s, t1 = 0, t2 = 0; float mFloat = 3.3f; int f, n1 = 0, n2 = 0; for (int i = 0; i < 1E4; i++) { switch ((int) (Math.random() * 2)) { case 0: n1 += 1E4; s = System.currentTimeMillis(); for (int k = 0; k < 1E4; k++) f = (int) (mFloat + 0.5); t1 += System.currentTimeMillis() - s; break; case 1: n2 += 1E4; s = System.currentTimeMillis(); for (int k = 0; k < 1E4; k++) f = Math.round(mFloat); t2 += System.currentTimeMillis() - s; break; } } System.out.println(String.format("(int) (mFloat + 0.5): n1 = %d -> %.3fms/1000", n1, t1 * 1000.0 / n1)); System.out.println(String.format("Math.round(mFloat) : n2 = %d -> %.3fms/1000", n2, t2 * 1000.0 / n2)); } }
Java SE6 output:
(int) (mFloat + 0.5): n1 = 500410000 -> 0.003ms/1000 Math.round(mFloat) : n2 = 499590000 -> 0.022ms/1000
Exit to Java SE7 (thanks to alex for the results):
(int) (mFloat + 0.5): n1 = 50120000 -> 0,002ms/1000 Math.round(mFloat) : n2 = 49880000 -> 0,002ms/1000
As you can see, there has been a significant performance improvement at the Math.round level from SE6 to SE7. I think that there are no more significant differences in SE7, and you should choose what seems more readable to you.
brimborium Aug 23 '12 at 12:13 2012-08-23 12:13
source share