Java – GC Optimization: for vs foreach
I've been trying to optimize some of my code and got a strange conclusion about fors
In my test case, I created a new project with major activities This activity initializes the list of 500 objects, runs an explicit GC, and starts the thread Thread loop function docalculations
this. Objects is a list of 500 myobjects, formerly MyObject, and value is int. functional logic has no logic, they are just doing anything The difference is inherent
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; }
Using function 2 GC is called every 10 seconds on my nexus, releasing ~ 1.7mb
Using function 1 GC will never be seen
Why?
Solution
One creates an iterator and the other does not
Is GC actually the bottleneck of your application? (it seems unlikely that many developers, including myself, will consider the benefits of readability more than a few microseconds of GC.)
In other words, your whole cycle is an insignificant response