I have a method which needs to return a Vector object. Now, I realize that I dont really need it to be a Vector here and an ArrayList would do the job too since i dont need a synchronized collection. However, due to framework limitations, the return type must be a vector.
I was wondering if I could improve performance if I add objects to an ArrayList, and convert it into a Vector by doing something like
List list = new ArrayList();
return new Vector(list);
Or would simply adding objects to a Vector be better than doing the above?
Can i create a non-synchronized subclass of Vector which I can return in my method?
Adding the Objects directly into Vector instance is enough...
Former approach leads to creation of ArrayList instance redundantly...
SCJP 6 [SCJP - Old is Gold]
Joined: Feb 22, 2011
From the source of Vector.java
Note:I haven't done any bench marking on whether creating ArrayList and then returning Vector(list) will have any notable performance improvement or not. So I am not really sure which one would be better. I feel returning Vector(list) may be good if the number of elements that needs to be added to the vector is high.
The (main) performance issue with the vector class (if initialized with the proper size) is the synchronization required while adding elements. However, a modern JVM (up to date 1.6+) will inspect your code and identify that you're just accessing a local instance without any chance of another thread interfering. Therefore, it will remove the synchronization overhead at runtime, so can probably just ignore the performance considerations in this case and directly add to the Vector instance.