Skip to content

Instantly share code, notes, and snippets.

@rzymek
Last active December 28, 2015 07:58
Show Gist options
  • Save rzymek/7467855 to your computer and use it in GitHub Desktop.
Save rzymek/7467855 to your computer and use it in GitHub Desktop.
`ArrayList` vs `Object[]` performance
package main;
import java.util.ArrayList;
import java.util.List;
public class Main {
private static final int RUNS = 10;
static List<String> list;
static String[] arr;
public static void main(String[] args) {
new Object() {
protected void finalize() throws Throwable {
System.err.println("GC did run");
System.exit(1);
};
};
final int count = Integer.MAX_VALUE / 100;
write(count);
read(count);
}
protected static void write(final int count) {
double listMs = measure(new Runnable() {
@Override
public void run() {
list = new ArrayList<>(count + 1);
for (int i = 0; i < count; i++)
list.add("str");
}
});
double arrMs = measure(new Runnable() {
@Override
public void run() {
arr = new String[count];
for (int i = 0; i < count; i++)
arr[i] = "str";
}
});
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).equals("xx")) {
System.out.println("err");
}
}
}
});
double arrMs = measure(new Runnable() {
@Override
public void run() {
for (int i = 0; i < count; i++)
if (arr[i].equals("xx")) {
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