0

I want to compare the add method (for 1000 elements) in the class Vector and in the class ArrayList.

Why is the add method in Vector faster then add method in ArrayList?

Here is the code I am using to measure:

public static void main(String[] args) {
    List v = new Vector();
    List l = new ArrayList();
    long startTime = System.nanoTime();
    for (int i = 0; i < 1000; i++) {
        v.add(i);
    }
    long duration = System.nanoTime() - startTime;
    System.out.println("Vector: " + duration + " ns");
    startTime = System.nanoTime();
    for (int i = 0; i < 1000; i++) {
        l.add(i);
    }
    duration = System.nanoTime() - startTime;
    System.out.println("ArrayList: " + duration + " ns");
}
Keppil
  • 45,603
  • 8
  • 97
  • 119
  • Did you compare the code? [ArrayList#add()](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/ArrayList.java#ArrayList.add%28java.lang.Object%29) and [Vector#add()](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/Vector.java#Vector.add%28java.lang.Object%29). – Keppil Dec 13 '14 at 13:18
  • import java.util.*; public class prova { public static void main(String[] args) { List v = new Vector(); List l = new ArrayList(); long startTime=System.nanoTime(); for (int i=0; i<1000; i++){ v.add(i); } long duration=System.nanoTime()-startTime; System.out.println("Vector: " + duration + " ns"); startTime=System.nanoTime(); for (int i=0; i<1000; i++){ l.add(i); } duration=System.nanoTime()-startTime; System.out.println("ArrayList: " + duration + " ns"); } } –  Dec 13 '14 at 13:19
  • Doing benchmarking is not simple as that you are doing. You need to take in account many factors (such as warmup, JIT optimizations, etc). Consider using a benchmark framework such as JMH to test. – Alexis C. Dec 13 '14 at 13:24
  • 1
    I get `Vector: 305213 ns, ArrayList: 240066 ns` woth your code. These kinds of microbenchmarks are very unreliable. – Keppil Dec 13 '14 at 13:24
  • please put it in the question – MightyPork Dec 13 '14 at 13:24
  • @Federica you better add this comment in your post, it easier to read then – Sybren Dec 13 '14 at 13:24

1 Answers1

1

The results are probably distorted due to JVM warmup. After running the test few times I have obtained the following results:

1553108 [ns]   → Vector.add()
1420628 [ns]  → ArrayList.add()

The benchmark was conducted for 10000 insertions.

Community
  • 1
  • 1
Kuba Rakoczy
  • 3,954
  • 2
  • 15
  • 16
  • When I compile my code, I obtain different results: in my output, Vector seems faster than ArrayList! How is it possible? Thank you!! –  Dec 14 '14 at 09:03