How Does The Performance Of Arraylist compare with Array

To read from an ArrayLists takes three time longer than reading from an Array.

results for iterating over the arrays via the for loop:

To read Integer[]  takes 1133201 nano seconds
To read ArrayList  takes 3669686 nano seconds

using the following code :

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class ArrayListvArray {

    private static final Integer INT_VALUE = 1000;

    public static Integer[] INT_ARRAY = new Integer[50000];
    public static List<Integer> ARRAY_LIST;

    public static void main(String... args) {

     // as the JVM warms up the times will improved

      for(;;) { 
        ARRAY_LIST = new ArrayList(Collections.nCopies(INT_ARRAY.length, INT_VALUE));
        Arrays.fill(INT_ARRAY, INT_VALUE);

        readFromArray();
        readFromArrayList();
      }

    }

    private static long readFromArray() {

        Integer j;
        long start = System.nanoTime();

        for (int i = 0; i < INT_ARRAY.length; i++) {
            j = INT_ARRAY[i];  //
        }
        long timeTaken = (System.nanoTime() - start);
        System.out.println("To read " + INT_ARRAY.getClass().getSimpleName() + " takes " + timeTaken + " nano seconds");
        return timeTaken;
    }

    private static long readFromArrayList() {

        Integer j;
        long start = System.nanoTime();
        for (int i = 0; i < INT_ARRAY.length; i++) {
            j = ARRAY_LIST.get(i);
        }
        long timeTaken = (System.nanoTime() - start);

        System.out.println("To read " + ARRAY_LIST.getClass().getSimpleName() + " takes " + timeTaken + " nano seconds");
        return timeTaken;
    }
}

The performance will very much depend on the VM involved, and a variety of other considerations.

The ArrayList is backed by an array, when storing data into the ArrayList, more work is performed, for example

A nullity check (to see whether the ArrayList reference is non-null).

A bounds check — to handle the resizing logic, to resize the array that backs its. This array is resized in chunks.
so the size of the list is usually smaller than the length of the array.

Potentially a virtual method indirection, depending on whether the JIT has managed to inline the call

Its worth noting that usually the performance of one single method call doesn't matter much, usually its not worth sacrificing good design for few micro-seconds. Only optimize your fast paths, its likely most of your code will be run infrequently.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License