Translate

Thursday, November 22, 2012

Java Performance in collection - 02



java.util.Map
Addition and Accession
Hashtable vs. HashMap


Addition

Hashtable ht = new Hashtable();
For(int I = 0; i
{
          ht.put(Integer.valuOf(i),Integer.valueOf(i));
}                                                                                     Takes 453 ms


HashMap hm = new HashMap();
For(int i=0;i
{
          hm.put(Integer.valueOf(i),Integer.valueOf(i));
}                                                                                     Takes 328 ms


Accession

Hashtable ht = new Hashtable();
For(int I = 0; i
{
          ht.get(Integer.valuOf(i));
}                                                                                     Takes 94 ms


HashMap hm = new HashMap();
For(int i=0;i
{
          hm.get(Integer.valueOf(i));
}                                                                                      Takes 47 ms


Hashtable vs. HashMap

Hashtable is synchronized so it is slower than HashMap


Exceptions, assertions, casts and variables

Include all error-condition checking in blocks guarded by if statements
•Avoid throwing exceptions in normal code path of your application
•Investigate whether a try-catch in the bottleneck imposes any extra cost
•Use instanceof instead of making any speculative class cast in a try-catch
Consider throwing exceptions without generating a stack trace by reusing a previously created instance
•Assertions add overheads, even when disabled
•Avoid (or do not use) assertions in a loop, frequently called methods
Avoid casts by using type specific collection classes
•Use temporary variables of the cast type, instead of repeated casting
•Prefer local variables to instance/static variables for faster manipulation
Use int in preference to any other datatypes
•Prefer primitive datatypes instead of objects for temporary variables

No comments: