4 ms·
The performance penality I'm talking about is far more tricky than just the little bit of overhead on a method vs a property. Take this simple data object as an
by RyanZAG 13y ago
The performance penality I'm talking about is far more tricky than just the little bit of overhead on a method vs a property. Take this simple data object as an example:
class Person {
public int age;
}
Now a 'best practice' is to create getters and setters:
class Person {
private int age;
public void setAge(int age) { this.age = age; }
public int getAge() { return this.age; }
}
This obviously makes the code uglier. This is done because maybe in the future you'd want to change the implementation of how age is stored inside the object. However, I think this is exactly where nasty performance bugs can slip in. Accessing 'age' or 'getAge()' are currently both O(1) operations with 'age' being slightly faster. However, 'age' will always be O(1) as guaranteed by the language, so using it inside a tight loop is fine. However, what happens if we modified our getAge() to be O(n) because we wanted to store age differently? eg:
class Person {
private List<Integer> subAges = ...;
public void setAge(int age) { ... }
public int getAge() {
int age = 0;
for (int subAge : subAges) {
age += subAge;
}
return age;
}
}
What we've done here is utilize our ability to change our getAge method without impacting anybody who is using our class. However, we've turned our getAge from O(1) to O(n) with absolutely no warning to anybody using our function. We've caused far more harm than simply requiring other developers to update their code - we've sabotaged the performance of all the users of all the software that uses our library.
So imo the 'benefit' you get from getters/setters is more of a danger than anything. If the implementation of a library changes enough that you need to change your data access objects, you should just release a completely new API anyway as all the assumptions made by users of your library are now right out the window.