0

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.

dfetter88
  • 5,381
  • 13
  • 44
  • 55

1 Answers1

0

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.

Fedor Skrynnikov
  • 5,521
  • 4
  • 28
  • 32
  • Yes, but I'm fairly certain that the final keyword also hints to the compiler that it can do optimizations on the variable. – dfetter88 Jul 06 '11 at 22:39
  • What do you mean by saying optimization. No it cant substitute function calls. Yes it is not needed to reload this variables from main memory. more here http://stackoverflow.com/questions/6602922/is-it-faster-to-access-final-local-variables-than-class-variables-in-java – Fedor Skrynnikov Jul 06 '11 at 23:05
  • Good to know. So the only way to avoid the function calls is by making member variables? – dfetter88 Jul 06 '11 at 23:25
  • the way to avoid multiple calls is to call only once. In your case it's better to compose all this separate variables and initialise them only once out of onDraw function. – Fedor Skrynnikov Jul 07 '11 at 10:26