OPT.DIC
Define initial capacities for `ArrayList', `HashMap', `HashSet', 'Hashtable', 'Vector', and `WeakHashMap'
Description
This rule flags any `ArrayList', `HashMap', `HashSet', 'Hashtable', 'Vector', or `WeakHashMap' whose initial capacity is not defined.
Expansion of Vector capacity involves allocating a larger array and copying the contents of the old array to the new one. Eventually, the old array object gets reclaimed by the garbage collector. Vector expansion is an expensive operation. The default 10-element capacity of a Vector is often not enough. Usually, you will be able to approximate the expected size; if so, you should use this value instead of the default.
Example
package OPT;
import java.util.Vector;
public class DIC {
public void addObjects (Object[] o) {
// if length > 10, Vector needs to expand
for (int i = 0; i< o.length;i++) {
v.add(o[i]); // capacity before it can add more ele-
ments.
}
}
public Vector v = new Vector(); // no initialCapacity.
}
Repair
Define initial capacity when known.
public Vector v = new Vector(20);
References
Bulka, Dov. Java Performance and Scalability Volume 1: Server-Side Programming Techniques. Addison Wesley, 2000. pp.55 - 57.
Ford, Neal. "Performance Tuning With Java Technology," JavaOne 2001 Conference.
|