Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GC optimization: for vs foreach

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?

like image 550
ggpuz Avatar asked Dec 21 '12 21:12

ggpuz


2 Answers

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.

like image 157
Louis Wasserman Avatar answered Oct 08 '22 00:10

Louis Wasserman


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

like image 20
MrSmith42 Avatar answered Oct 08 '22 01:10

MrSmith42