Last active
December 28, 2015 07:58
-
-
Save rzymek/7467855 to your computer and use it in GitHub Desktop.
`ArrayList` vs `Object[]` performance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main; | |
import java.util.ArrayList; | |
import java.util.List; | |
public class Main { | |
private static final int RUNS = 10; | |
static List<Integer> list; | |
static int[] arr; | |
public static void main(String[] args) throws Exception { | |
notifier(); | |
final int count = Integer.MAX_VALUE / 100; | |
write(count); | |
read(count); | |
} | |
protected static void notifier() { | |
new Object() { | |
protected void finalize() throws Throwable { | |
System.err.println("GC did run"); | |
notifier(); | |
}; | |
}; | |
} | |
protected static void write(final int count) throws Exception { | |
double listMs = measure(new Runnable() { | |
@Override | |
public void run() { | |
list = new ArrayList<>(count + 1); | |
for (int i = 0; i < count; i++) | |
list.add(i); | |
} | |
}); | |
System.gc(); | |
Thread.sleep(1000); | |
double arrMs = measure(new Runnable() { | |
@Override | |
public void run() { | |
arr = new int[count]; | |
for (int i = 0; i < count; i++) | |
arr[i] = i; | |
} | |
}); | |
System.out.println("list:" + listMs); | |
System.out.println("arr: " + arrMs); | |
} | |
protected static void read(final int count) { | |
double listMs = measure(new Runnable() { | |
@Override | |
public void run() { | |
for (int i = 0; i < count; i++) { | |
if (list.get(i) == -1) { | |
System.out.println("err"); | |
} | |
} | |
} | |
}); | |
double arrMs = measure(new Runnable() { | |
@Override | |
public void run() { | |
for (int i = 0; i < count; i++) | |
if (arr[i] == -1) { | |
System.out.println("err"); | |
} | |
} | |
}); | |
System.out.println("list read:" + listMs); | |
System.out.println("arr read: " + arrMs); | |
} | |
public static double measure(Runnable run) { | |
long[] times = new long[RUNS]; | |
for (int i = 0; i < times.length; i++) { | |
System.out.print("."); | |
long start = System.currentTimeMillis(); | |
run.run(); | |
long end = System.currentTimeMillis(); | |
times[i] = end - start; | |
} | |
System.out.println(); | |
int sum = 0; | |
for (long l : times) { | |
sum += l; | |
} | |
return (double) sum / times.length; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment