gpt4 book ai didi

java - Android 性能 - 'Avoid Internal Getters/Setters'

转载 作者:IT老高 更新时间:2023-10-28 20:32:39 24 4
gpt4 key购买 nike

只需在开发网站上阅读此内容:

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.

2019/05 更新:在当前版本中,上述 Material 已从文档中删除!

也就是说你会在类中使用字段访问:

 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 对性能的影响也适用于外部 getter 和 setter。

但是,在外部情况下,getter 和 setter 在其他领域具有显着优势;例如保留封装、减少有害耦合、使您的代码更易于维护等等。因此,尽管可能会导致性能下降,但使用 getter 和 setter 通常被认为是最佳实践

性能下降是由于旧版 Android JIT 编译器的限制所致。这种情况在使用 Gingerbread 后得到了显着改善(请参阅 - https://stackoverflow.com/a/4930538/139985 ...并注意谁写了这个答案!)并继续改善。事实上,在当前 (2019) 版本的 Performance Tips 中,有关内部 getter 和 setter 的整个部分已被删除。

一般来说,为劣质平台“调整”代码是个坏主意,尤其是在有可能出现更好的平台时。

关于java - Android 性能 - 'Avoid Internal Getters/Setters',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6716442/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com