Performance Issues (adding element to a Vector)

30 November 2007

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.

		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.

del.icio.us:Performance Issues (adding element to a Vector)  digg:Performance Issues (adding element to a Vector)  spurl:Performance Issues (adding element to a Vector)  wists:Performance Issues (adding element to a Vector)  simpy:Performance Issues (adding element to a Vector)  newsvine:Performance Issues (adding element to a Vector)  blinklist:Performance Issues (adding element to a Vector)  furl:Performance Issues (adding element to a Vector)  reddit:Performance Issues (adding element to a Vector)  fark:Performance Issues (adding element to a Vector)  blogmarks:Performance Issues (adding element to a Vector)  Y!:Performance Issues (adding element to a Vector)  smarking:Performance Issues (adding element to a Vector)  magnolia:Performance Issues (adding element to a Vector)  segnalo:Performance Issues (adding element to a Vector)  gifttagging:Performance Issues (adding element to a Vector)

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)

One Response to “Performance Issues (adding element to a Vector)”

  1. Dim Says:

    ArrayList (or better LinkedList) should be considered :-)

Leave a Reply