I just came across a weird effect and while tracking it down, I noticed that there seems to be a substantial performance difference for collecting inner vs. static nested classes. Consider this code fragment:
public class Test {
private class Pointer {
long data;
Pointer next;
}
private Pointer first;
public static void main(String[] args) {
Test t = null;
for (int i = 0; i < 500; i++) {
t = new Test();
for (int j = 0; j < 1000000; j++) {
Pointer p = t.new Pointer();
p.data = i*j;
p.next = t.first;
t.first = p;
}
}
}
}
So what the code does is create a linked list using an inner class. The process is repeated 500 times (for testing purposes), discarding the objects used in the last run (which become subject to GC).
When run with a tight memory limit (like 100 MB), this code takes about 20 minutes to execute on my machine. Now, by simply replacing the inner class with a static nested class, I can reduce the runtime to less than 6 minutes. Here are the changes:
private static class Pointer {
and
Pointer p = new Pointer();
Now my conclusions from this little experiment are that using inner classes makes it much more difficult for the GC to figure out if the objects can be collected, making static nested classes more than 3x faster in this case.
My question is if this conclusion is correct; if yes what is the reason, and if no why are inner classes so much slower here?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…