View RSS Feed

My Java Tips

Performance Issues (adding element to a Vector)

Rate this Entry
by , 11-09-2011 at 05:43 PM (1127 Views)
Adding 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.

Java Code:
		Vector vec = new Vector();

		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.

Submit "Performance Issues (adding element to a Vector)" to Facebook Submit "Performance Issues (adding element to a Vector)" to Digg Submit "Performance Issues (adding element to a Vector)" to del.icio.us Submit "Performance Issues (adding element to a Vector)" to StumbleUpon Submit "Performance Issues (adding element to a Vector)" to Google

Tags: None Add / Edit Tags
Categories
Performance

Comments