by, 11-13-2011 at 12:48 PM (1244 Views)
In this post, I will talk about the performance issues related to vector capacity. I have noticed, that normally developers donít care about the performance issues and declare the vector as:
Java Code:Vector vector = new Vector();
Newly created vector has no element in it so its size is 0 but its capacity is 10 by default. So if you donít specify the capacity of the vector (and call the default constructor), its capacity will be 10. Capacity of the vector is the maximum amount of objects a vector can hold before extension.
Vector expansion is an expensive operation. A larger array is created, contents of old array are moved on to newly created array and then the old array is gets reclaimed by garbage collector. So, the programmer should try to reduce Vector expansion scenarios if elimination is not possible.
In the example above, we created a Vector with initial capacity of 100. Here we have not specified the expansion/growth factor. By default, the Vectorís capacity will double with every expansion.Java Code:Vector vector = new Vector(100);
This is another way of declaring Vector. Here vector has initial capacity of 100 and will grow capacity by increments of 25 elements per expansion.Java Code:Vector vector = new Vector(100,25);
Talking about performance, initial capacity and growth factor are very important. One should try to minimize the need for expansion. Its an ideal scenario, that no expansion is required but one should also not declare a vector of initial capacity too large as compared to usage. For instance if you know that a vector will contain from 100 to 200 objects, then declaring a vector of 1000 capacity is not good at all.
So the conclusion is, do proper study and come up with proper and realistic estimates before declaring vectors. These things are usually ignored but they do make a difference.