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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With