Reputation: 2135
Why version4
method throws out of memory error but version3
method doesn't throw it, I think in both the cases there is problem is "obsolete reference"?
private static void version4() {
int count = 0;
long start = System.nanoTime();
try {
List<Calendar> list = new ArrayList<>();
System.out.println(list.size());
while(true){
for (int i = 0; i < 1000; i++) {
Calendar calendar = Calendar.getInstance();
list.add(i, calendar);
}
}
} catch (Error e) {
e.printStackTrace();
}
long end = System.nanoTime();
System.out.println("count: " + count + " | time:" + (end - start)/1000000);
}
private static void version3() {
int count = 0;
long start = System.nanoTime();
try {
Calendar[] calendars = new Calendar[1000];
while(true){
for (int i = 0; i < calendars.length; i++) {
Calendar calendar = Calendar.getInstance();
calendars[i] = calendar;
}
}
} catch (Error e) {
e.printStackTrace();
}
long end = System.nanoTime();
System.out.println("count: " + count + " | time:" + (end - start)/1000000);
}
Upvotes: 0
Views: 115
Reputation: 131346
In both cases you loop forever because of the outer while (true)
.
But in the array case, in the inner loop you overwrite old values of the array (that has a length of 1000). So the memory consumption is about constant.
While in the ArrayList
case you add new Calendar
objects in the inner loop. So the memory usage grows constantly : 1000 (first loop) + 1000 (second loop) + ...
Upvotes: 3