Here is an experiment. I wanted to see if a HashMap can retrieve a value faster than a call to Math.round. I found that Math.round is faster.
import java.util.HashMap;
public class Program {
public static void main(String[] args) {
// Place a Double key in this HashMap.
HashMap<Double, Long> roundCache = new HashMap<>();
double value = 1000.5;
roundCache.put(value, Math.round(value));
long t1 = System.currentTimeMillis();
// Version 1: use round.
for (int i = 0; i < 1000000; i++) {
for (int y = 0; y < 200; y++) {
// Use Math.round method directly.
long result = Math.round(value);
if (result != 1001) {
return;
}
}
}
long t2 = System.currentTimeMillis();
// Version 2: use get() to look up a value.
for (int i = 0; i < 1000000; i++) {
for (int y = 0; y < 200; y++) {
// Use get.
long result = roundCache.get(value);
if (result != 1001) {
return;
}
}
}
long t3 = System.currentTimeMillis();
// ... Times.
System.out.println(t2 - t1);
System.out.println(t3 - t2);
}
}
7 ms: Math.round calls
358 ms: HashMap get calls