Android Dev: Avoiding Internal Getters/Setters?

I was reading this section in the Android Dev Guide :

here

and I was wondering what is a "Virtual method call" and what does it mean when it says "locally" using a getter/setter? I'm trying to figure out if what they're saying is avoid using methods EVER (for instance a method from an instanced object) or just inside a class you're already working in to get a variable?

To sum it up basically, if I'm in a different class and I want to know the value of a variable in a different class will it be more expensive to do otherclass.getX() than to do otherclass.x ? Or is it the same performance if it's not within the current class to do either a method or access a public variable directly?


Using getters and setters is more expensive because first the VM will lookup the method from a virtual method table and then make the call. For faster access on Android directly accessing member variables reduces the overhead


In that article, they are referring internally accessing private members, and doing so with the field directly rather than calling getX() inside the same class.

It is still recommended (and common) to make members private and provide public accessor methods for external use.

HTH


What the article is basically saying is to avoid the getter/setter patten when you can get away with it. In Java, all methods are Virtual that aren't marked with the private or final modifiers, so they are saying that if your code isn't interface to be implemented by other classes, just access the fields directly. Most likely the reason they point this out is because traditionally, the Java recommendation has been to always use the getter / setter pattern so that your variables can be kept private. However, in Android, you can take a pretty severy performance hit if you add this additional layer of abstraction.

So, in summary. If you're creating an API that other classes will implement, then maybe it's worth it to take the performance hit of getters / setters. But, in your own classes that all interact with each and you're not enforcing a contract, just access the variables directly. External classes accessing your class will also experience the same performance gain by accessing the variable directly, but at some point you need to do a performance-to-maintainability assessment to see if you are comfortable making those variables public or if it's worth it to take the hit and use getter / setter methods

链接地址: http://www.djcxy.com/p/23676.html

上一篇: 访问本地字段vs对象字段。 doc是错误的吗?

下一篇: Android开发人员:避免内部获取者/设置者?