Androidのエンティティクラスの正しい使い方

1682 ワード

エンティティークラスはAndroid開発でよく使われるものですが、今日聞いたばかりで、元のAndroidのエンティティークラスの使い方がJavaのエンティティークラスの使い方と同じではないことがわかりました.
以前javaの基礎を学んだとき、実体クラスというものはすべてこうだったことを知っていました.まずクラスを建てて、それからいくつかのプライベート属性を設定して、getとsetの方法で外部に呼び出して、Androidに着いても同じように使いましたが、実はAndroidでは推薦しません.
Androidで推奨されるエンティティクラスは属性公有であり、getやsetで呼び出す必要はなく、外部で直接使用することができ、属性私有のgetやsetで呼び出す書き方よりも速度が3倍速い.
具体的な詳細は公式の紹介説明を参考にすることができます.これは原文です.
Avoid Internal Getters/Setters
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.
参照リンク:http://developer.android.com/training/articles/perf-tips.html#GettersSetters
http://developer.android.com/training/articles/perf-tips.html