I tried the following to test the performance of array and ArrayList. I know That arrayList is backed-up by array, but i saw strange behavior while accessing the data from list and array as mentioned below.. I would like to understand why this behavior? Doesn't the creating ArrayList with initial capacity improve performance, or am i doing any mistake?. I did not find any improvement on performance while adding the elements.
The output of below program is given below
time taken to add elements 1
time taken to print elements 229
LIST: time taken to add elements 10 // it is same even i set the initial capacity by passing as arg to constructor.
LIST: time taken to print elements 161
I have omitted the print statements as its taking space.
I see, its a duplicate post, however, posting as it is giving different behavior while retrieving.
package com.samples.misc;
import java.util.ArrayList;
import java.util.List;
public class ArrayTest {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
int a[] = new int[50000];
for(int i=0;i<a.length;i++)
a[i] = i;
long endTime = System.currentTimeMillis();
System.out.print("time taken to add elements "+(endTime - startTime));
System.out.println();
startTime = System.currentTimeMillis();
for(int i=0;i<a.length;i++)
System.out.print(a[i]);
endTime = System.currentTimeMillis();
System.out.println();
System.out.println("time taken to print elements "+(endTime - startTime));
System.out.println();
startTime = System.currentTimeMillis();
List<Integer> integers = new ArrayList<Integer>();
//List<Integer> integers = new ArrayList<Integer>(50000); this does not make any diff, it takes same amount of time to add elements, whats the use case of this?
for(int i=0;i<50000;i++){
integers.add(i);
}
endTime = System.currentTimeMillis();
System.out.println("LIST: time taken to add elements "+(endTime - startTime));
System.out.println();
startTime = System.currentTimeMillis();
for(int i=0;i<a.length;i++)
System.out.print(integers.get(i));
endTime = System.currentTimeMillis();
System.out.println();
System.out.println("LIST: time taken to print elements "+(endTime - startTime));
}
}