Performance Issues (adding element to a Vector)
30 November 2007Adding elements to a Vector is a normal practice but there are few performance issues related to this which should be considered.
Elements can be added to Vector using any of the following:
- insertElementAt(e, index)
- addElement(e)
- add(e)
- add(index,e)
The addElement(e) and add(e) methods are used to add elements at the end of Vector whereas insertElementAt(e, index) and add(index, e) methods are used to insert element at any index of the Vector.
Vector <String>vec = new Vector<String>(); vec.add("String1"); vec.add("String2"); vec.addElement("String3"); vec.addElement("String4"); vec.add(0, "String5"); vec.add(1, "String6"); vec.insertElementAt("String7", 1); vec.insertElementAt("String8", 0); for(String s:vec) { System.out.println(s); }
Output:
String8 String5 String7 String6 String1 String2 String3 String4
Thing to note is that vector stores elements in continuous memory locations. Now if you add element at the end of Vector, then no shift is required for other elements. But if you add an element at some other place, shift operation is required. For example, if a Vector has 9 elements and you plan to add an element at the 1st place (0th index), then 9 shifts are required, which is a costly operation. And if you add it at the end of the Vector, then there is no shift required.
So, use insertElementAt(e, index) or add(index,e) if really required.
I hope this helps.
Related Posts:
- Vector Capacity
- LinkedList - insertion/deletion
- Autoboxing And Unboxing in Java 5
- Java built-in data types (performance issues)
- Java IO tasks
- Java performance Issues (I)
- Using Vectors
- Performance issues related to trigonometric functions , floating point arithmetic and JNI (I)
- Using TreeSet
- Using Vectors in Java
Top Of Page | Trackback
If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.
It will look like this: Performance Issues (adding element to a Vector)
ArrayList (or better LinkedList) should be considered