onDraw() 方法中的最终变量

发布于 2024-11-19 04:58:33 字数 731 浏览 2 评论 0原文

我有一个扩展 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

心舞飞扬 2024-11-26 04:58:33

在这里说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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文