onDraw() 方法中的最终变量
我有一个扩展 View
并重写 onDraw(Canvas canvas)
方法的类。该视图运行动画,因此 onDraw
每秒将被调用多次。考虑以下示例...
@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);
...
}
我是否应该担心每次调用 onDraw
时都会发生这么多函数调用? final
是否告诉编译器不需要每次都调用这些函数?这些变量作为成员变量
是否会更好,以便函数仅被调用一次?
PS 我通过运行我的程序知道性能不受影响。我是从学习的角度问这个问题的。当我确切地知道自己在做什么时,这会让我感觉更好。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在这里说final只是说这个局部变量不会在这个函数中改变,并且每次调用onDraw时都会调用函数。
如果可能的话,最好将所有这些变量组合到另一个类(如 DisplayProperties)中,并仅初始化一次。
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.