Calling a getter multiple times or calling once and assigning to a variable?

后端 未结 13 1718
无人共我
无人共我 2021-02-05 15:26

say suppose I have class as :

public class Age {

    private int age;

    public int getAge() {
       return this.age;
    }

}

In my Main c

相关标签:
13条回答
  • 2021-02-05 16:01

    For a simple case like this, I'd go for the one that looks best code-wise.

    There are a few cases where it is advisable to call once and read the saved return value, such as in

    for (int i = 0; i < list.size(); i++)
        doSomethingThatDoesNotAffectSizeOfList();
    

    since the compiler may have trouble figuring out if the body of the loop affects the size of the list. A properly implemented list should always be able to tell it's size easily, but in other examples (or when dealing with poorly implemented collections) it might be worse.

    In general, if a method is computationally heavy, you could use memoization, which basically means that you cache already computed input / output values.

    A memoized function "remembers" the results corresponding to some set of specific inputs. Subsequent calls with remembered inputs return the remembered result rather than recalculating it, thus eliminating the primary cost of a call with given parameters from all but the first call made to the function with those parameters.

    This technique pushes the "save-the-return-value-for-efficiency" into the method itself, which eases the maintenance bla bla bla...

    0 讨论(0)
提交回复
热议问题