Setter and Getter functions. In Android. Performance overhead? Setter and Getter functions. In Android. Performance overhead? android android

Setter and Getter functions. In Android. Performance overhead?


As of the documentation found here using a getter and setter is a bad idea in android. As it says,

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.

Find more about performance here.


According to the performance tips provided by Google android team:

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.

However I do agree that a good coding practice is more important and the team also mentioned that:

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

Therefore I think it's ok to use the getter and setter ;)

Reference


The performance loss for setters and getters is negligible. Public fields are bad practice and violate the object oriented principles of data encapsulation and information hiding.

Using a setter or getter requires one property call more than accessing the field directly. That's nothing, so don't worry about it--focus on writing good code.

edit:

To clarify, this is from the same android document that the other posters are quoting:

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.

In other words, you still need getters and setters. You just should try to avoid calling them from within the class that holds those methods since you have direct access to the field.