微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

android – 避免内部Getters/Setters

在Activity. java的源代码中,我看到了一些方法
public View findViewById(int id) {
    return getwindow().findViewById(id);
}

和getwindow方法的定义:

public Window getwindow() {
    return mWindow;
}

但是按照以下规则:

Avoid Internal Getters/Setters

In native languages like C++ it’s
common practice to use getters (e.g. i
= getCount()) instead of accessing the field directly (i = mCount). This is
an excellent habit for C++,because
the compiler can usually inline the
access,and if you need to restrict or
debug field access you can add the
code at any time.

On Android,this is a bad idea.
Virtual method calls are expensive,
much more so than instance field
lookups. It’s reasonable to follow
common object-oriented programming
practices and have getters and setters
in the public interface,but within a
class you should always access fields
directly.

Without a JIT,direct field access is
about 3x faster than invoking a
trivial getter. With the JIT (where
direct field access is as cheap as
accessing a local),direct field
access is about 7x faster than
invoking a trivial getter. This is
true in Froyo,but will improve in the
future when the JIT inlines getter
methods.

所以我想知道为什么android开发人员不能直接访问这个mWindow对象?如果当前Android版本的JIT无法内联访问,则getwindow().findViewById(id)将比mWindow.findViewById(id)花费更多时间,而findViewById是一种相当常用的方法.

解决方法

您无法直接访问mWindow属性it’s private.
而且我不关心findViewById的速度,因为您只需要在onCreate()方法中为布局中的每个视图调用一次,并将视图存储在活动成员中.你每个视图只调用一次findViewById,不是吗?

原文地址:https://www.jb51.cc/android/314580.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐