java – Android性能 – “避免内部Getters / Setters” - 代码日志

java – Android性能 – “避免内部Getters / Setters”

只需在开发者网站上阅读:

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.

那就是说你会在课堂上使用现场访问:

 public class MyObject {

    public Object innerObject; // This would be private if I was using a getter

    public void doSomeStuff(){
          if(innerObject){        // Within class access like this
                 // ....
          }
    }

    public Object getInnerObject(){  // This would be removed if I was using field access
         return innerObject;
    }
 }

但是从另一个对象访问呢?

 public class SecondObject {

      public void doSecondSomething(){
                MyObject ob = new MyObject();
                Object inner;

                //This is my question basically (from an Android performance perspective)   
                inner = ob.getInnerObject();
                // OR 
                inner = b.innerObject

       }

 }
使用内部吸气器和设定器的性能也适用于外部吸气器和设定器。

然而,在外部情况下,吸气器和定位器在其他领域有显着的效益;例如保护封装,减少有害耦合,使您的代码更易于维护等等。所以,尽管可能会发生这样的表现,一般认为使用getter和setter是最佳实践。

性能下降是由于旧版Android JIT编译器的限制而导致的。这种情况肯定会改善姜饼的改善。 (参考 – http://stackoverflow.com/a/4930538/139985 …并注意谁写了那个答案!)

一般来说,“调整”你的代码是一个劣质的平台是一个坏主意,特别是如果有合理的机会,一个更好的一个是在处理。

http://stackoverflow.com/questions/6716442/android-performance-avoid-internal-getters-setters

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:java – Android性能 – “避免内部Getters / Setters”