Search code examples
javaperformanceclasspojomember-variables

Should I create a new variable or always access the data from a class object?


Let's begin with an example (just for the sake of explanation)

public void mySecretOperation() {
    User user = new User();

    if (user.getAge() > 2 && user.getAge() < 5) {
        //TODO : do something...
    }

    if (user.getAge() > 12 && user.getAge() < 15) {
        //TODO : do something...
    }

    if (user.getAge() > 31 && user.getAge() < 55) {
        //TODO : do something...
    }

    if (user.getAge() > 78 && user.getAge() < 89) {
        //TODO : do something...
    }

}

Another alternative is int age = user.getAge(); and then use age everywhere instead of user.getAge().

  • So, performance wise (or let's consider space complexity) will there be any difference?

  • Can we say that one approach is better than other?

I know its a noob question, still curious to know.


Solution

  • Even though it make a difference performance wise, that's almost negligible. So performance wise you won't get much by refactoring.

    Since you are not doing any logical operations (like increasing/decreasing etc..) after receiving, it's okay to invoke getter multiple times. After all there is a variable that you are getting which is returning by that method.

    Unless you are doing some costly operations inside your getter, your code looks ok to me.

    Note that, if you are in multi threaded environment, it's ways better to use the getter, since there are chances of modifications of the variable you are getting.