java: List.contains() performance difference with manual searching

Viewed 22524

I tried to demonstrate the difference between List.contains() and manually searching execution times the result is awesome. Here is the code,

public static void main(String argv[]) {
    List<String> list = new ArrayList<String>();
    list.add("a");
    list.add("a");
    list.add("a");
    list.add("a");
    list.add("a");
    list.add("a");
    list.add("b");

    long startTime = System.nanoTime();

    list.contains("b");

    long endTime = System.nanoTime();
    long duration = endTime - startTime;

    System.out.println("First run: "+duration);

    startTime = System.nanoTime();
    for(String s: list){
        if(s.equals("b"))
            break;
    }
    endTime = System.nanoTime();

    duration = endTime - startTime;
    System.out.println("Second run: "+duration);

}

Output:

  • First run: 7500
  • Second run: 158685

    1. how contains() function makes such a big difference?

    2. which search algorithm does it use?

    3. if list conatins the searched element, does it terminate searching at first element?

3 Answers
Related