Skip to content

Instantly share code, notes, and snippets.

@cgbystrom
Created May 8, 2011 12:51
Show Gist options
  • Save cgbystrom/961354 to your computer and use it in GitHub Desktop.
Save cgbystrom/961354 to your computer and use it in GitHub Desktop.
Compare iteration over native array vs ArrayList (JVM playing tricks on me?)
import java.util.ArrayList;
public class TestArrayIteration {
public static void testArray() {
Integer[] arr = new Integer[1000];
for (int i = 0; i < 1000; i++) {
arr[i] = 1;
}
int total = 0;
long start = System.currentTimeMillis();
for (int j = 0; j < 10000000; j++) {
for (int i = 0; i < 1000; i++) {
total += arr[i];
}
}
long end = System.currentTimeMillis();
System.out.println("Array took " + (end - start));
}
public static void testArrayList() {
ArrayList<Integer> arr = new ArrayList<Integer>(1000);
for (int i = 0; i < 1000; i++) {
arr.add(i, 1);
}
int total = 0;
long start = System.currentTimeMillis();
for (int j = 0; j < 10000000; j++) {
for (int i = 0; i < 1000; i++) {
total += arr.get(i);
}
}
long end = System.currentTimeMillis();
System.out.println("ArrayList took " + (end - start));
}
public static void main(String[] args) {
testArray(); // Output: array took 9692
testArrayList(); // Output: ArrayList took 13550
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment