I have a method 3 levels down in the call stack of an onDraw() method. It is called hundreds, sometimes thousands of times per redraw. I’ve done extensive profiling of the onDraw() method and I can see that the following method is taking 14% of the total so definitely worth looking at. I need to get my frame rates up during pinch zoom and drag operations.
private void getVisiblePointsFromPath(){
double longRads = longitude * (Math.PI / 180);
double latRads = latitude * (Math.PI / 180);
...
}
When the method exits and the doubles go out of scope, I assume that they become eligible for GC although I recognise when this might happen is non-deterministic.
Is there anything to gain 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 the doubles to be nulled then reassigned on each pass but will not result in additional garbage and thus reduce the amount of GC I’m causing. Or is the VM smarter than that?
Please note that my question is not “which is faster” per se, it’s about which is likely to lead to less GC. I can measure the speed difference but I don’t understand enough of the Dalvik VM and Android GC to predict which causes less garbage.
Primitive local variables live on the stack, not the heap, so they don’t need to be GC’d at all. They are effectively gone as soon as the function returns – because that clears the stack frame.
That said, yes, the doubles will be reassigned on each pass, because that’s what the code you’ve written says to do. If you want to increase the speed of this particular method, calculate
longRadsandlatRadswhenlongitudeandlatitudeare set. The right way to do this is to always delegate setting those fields to a setter method. For example:This will, of course, make setting a slower operation, but that’s not what you asked about optimizing.