Search code examples
javaandroidfinalmicro-optimization

Final variables in onDraw() method


I have a class that extends View and overrides the onDraw(Canvas canvas) method. This view runs animations, so onDraw will be called many times per second. Consider the following example...

@Override
protected void onDraw(Canvas canvas) {
  final int width = getWidth();
  final int height = getHeight();

  final int padLeft = getPaddingLeft();
  final int padTop = getPaddingTop();
  final int padRight = getPaddingRight();
  final int padBottom = getPaddingBottom();

  final RectF oval = new RectF(padLeft, padTop, width - padRight, height - padBottom);
  ...
}

Should I be worried that there are this many function calls happening each time onDraw is called? Does final tell the compiler that it doesn't need to call these functions each time? Would these variables be better off as member variables so that the functions are only called once?

P.S. I know from running my program that performance is not affected. I am asking this question from a learning standpoint. It makes me feel better when I know exactly what I'm doing.


Solution

  • by saying final here you just saying that this local variable will not be changed in this function and functions will be called each time you call onDraw. If it is possible it's better to compose all this variables to another class like DisplayProperties and initialise it only once.