Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Vector performance

 
Ashish Bassi
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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();
list.add(obj1);
list.add(obj2);
list.add(obj3);
...

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?





 
Ram Narayan.M
Ranch Hand
Posts: 247
Chrome Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Adding the Objects directly into Vector instance is enough...

Former approach leads to creation of ArrayList instance redundantly...

 
Sudheer Bhat
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Alexander Kober
Ranch Hand
Posts: 32
IntelliJ IDE Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic