Android 实体类正确使用

学习java的时候,都知道实体类都是这么生成的:先建一个类,设置私有属性,然后生成get和set方法。

但是,在Android中并不推荐,Android推荐使用实体类是属性公有,不必通过get和set调用,而是外界直接使用,这样写在速度上会比属性私有的那种通过get和set方式调用快3倍。

In native languages like C++ it's common practice to use getters (i = getCount()) instead of accessing the field directly (i = mCount). This is an excellent habit for C++ and is often practiced in other object oriented languages like C# and Java, 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.

However, this is a bad idea on Android. 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.

Note that if you're using ProGuard, you can have the best of both worlds because ProGuard can inline accessors for you.

你可能感兴趣的:(Android,Android实体类)