GC effect of using local variables compared to fields

I have a level 3 method down in the call stack of the onDraw () method. It is called hundreds, sometimes thousands of times, for redrawing. I did extensive profiling of the onDraw () method, and I see that the next method takes 14% of the total amount that is definitely worth a look. I need to increase the frame rate during zoom and drag operations.

private void getVisiblePointsFromPath(){ double longRads = longitude * (Math.PI / 180); double latRads = latitude * (Math.PI / 180); ... } 

When a method exits and doubles out of scope, I assume that they become available to the GC, although I find out that this can happen, is not deterministic.

Is there anything you can get by doing this:

 public class GisView extends ImageView{ private double longRads; private double latRads; private void getVisiblePointsFromPath(){ longRads = longitude * (Math.PI / 180); latRads = latitude * (Math.PI / 180); ... } } 

I assume that this idiom will cause duplicates to be null and then reassigned in each pass, but will not result in extra garbage and thus reduce the amount of GC that I call. Or is a VM smarter than that?

Please note that my question is not “one that’s faster” in itself, but this is likely to lead to less GC. I can measure the difference in speed, but I don’t understand enough what the Dalvik VM and Android GC predict, which causes less junk.

+4
source share
1 answer

I assume that this idiom will cause duplicates to be null and then reassigned in each pass, but will not result in extra garbage and thus reduce the amount of GC that I call. Or is a VM smarter than that?

Primitive local variables live on the stack , not a bunch, so they should not be GC'd at all. They effectively go away as soon as the function returns, because it clears the stack frame.

However, yes, doubles will be reassigned in each pass, because that is what is written in the code you wrote. If you want to increase the speed of this particular method, calculate longRads and latRads when longitude and latitude . The proper way to do this is to always allow the delegate to set these fields to the setter method. For instance:

 public void setLongitude(double longitude) { this.longitude = longitude; this.longRags = longitude * (Math.PI / 180); } 

This, of course, will make setting up a slower operation, but that’s not what you asked for optimization.

+7
source

All Articles