Reputation: 311
I've been trying to optimize some of my code, and ive reached a strange conclusion regarding fors.
In my testcase ive created a new project with main activity. The activity initializes a List of 500 objects, runs an explicit GC and starts the thread. The thread loops the function doCalculations.
this.objects is a list of 500 MyObject, previous is MyObject, value is int. The function logics hold no logic, they are just there to do stuff. The difference is in the inner for.
function1
public void doCalculations()
{
for(MyObject o : this.objects)
for(int i=0; i<this.objects.size(); i++)
if(this.objects.get(i) == o)
o.value = this.objects.get(i).value;
}
function 2
public void doCalculations()
{
for(MyObject o : this.objects)
for(MyObject o2 : this.objects)
if(o2 == o)
o.value = o2.value;
}
With function 2 GC is called every ~10 secs on my nexus s, freeing ~1.7MB.
With function 1 GC is never to be seen.
Why is that?
Upvotes: 10
Views: 988
Reputation: 10151
My suggestion is that' because the inner for-loop creates an Iterator for each run of the outer for loop (in function 2). This Iterator-instances are not created in function 1
Upvotes: 3
Reputation: 198033
One creates an iterator, the other doesn't.
Is the GC actually a bottleneck in your application? (It seems unlikely. Many devs, myself included, would consider the readability benefit to outweigh a few microseconds of GC.)
That said, your entire loop is a no-op anyway.
Upvotes: 10