I want a map whose get operation is as fast as possible.
The key is set of string (2 table names in database which are related) and value is a integer (the number is id of row in database which has actual relationship between tables),
example :
table 1 - employee
table 2 - company
relationship - employee.comp_id = company.id
I have no intentions to read keys in the map. I just want the relationship id for the given 2 table names. so I wrote a small program to test get operation in HashMap.
public static void main(String args[]) throws NoSuchMethodException, SecurityException {
int limit = 1000;
HashMap<Integer, Integer> m1 = new HashMap<>(1000 * 1000);
HashMap<Set<String>, Integer> m2 = new HashMap<>(1000 * 1000);
String k1, k2;
Set<String> k3;
Integer k4;
for (int x = 0; x < limit; x++) {
for (int y = 0; y < limit; y++) {
k1 = String.valueOf(x);
k2 = String.valueOf(y);
k3 = new HashSet<>(Arrays.asList(k1, k2));
k4 = k3.hashCode();
m2.put(k3, k4);
m1.put(k4, k4);
}
}
long t1, t2;
System.out.println("init");
t1 = System.nanoTime();
// block 1 /////////////////////////////////////////////
for (int x = 0; x < limit; x++) {
for (int y = 0; y < limit; y++) {
m1.get(new HashSet<>(Arrays.asList(String.valueOf(x),
String.valueOf(y))).hashCode());
}
}
// /////////////////////////////////////////////////////
t2 = System.nanoTime();
System.out.println(t2 - t1);
t1 = t2;
// block 2 /////////////////////////////////////////////
for (int x = 0; x < limit; x++) {
for (int y = 0; y < limit; y++) {
m2.get(new HashSet<>(Arrays.asList(String.valueOf(x),
String.valueOf(y))));
}
}
// /////////////////////////////////////////////////////
t2 = System.nanoTime();
System.out.println(t2 - t1);
}
On my machine block 2 takes approximately 9 times more time than block 1 to complete execution.
Is the performance dependent on complexity of the Object used as key.
in either case I know hashcode is calculated by the impementation of HasMap.get() method.
Actually for code in block 1 hashcode is calculated by my code as well as implementation of HashMap, but still the performance is better than block 2 where hashcode of the Set is computed only by implementation of HashMap.
notice that Set is being created in both blocks
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…