Calling a getter multiple times or calling once an

2019-03-15 06:02发布

say suppose I have class as :

public class Age {

    private int age;

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

}

In my Main class I am calling the getAge() method many times.

So I wanted to know is it advisable to call so many times or call once and assign it to some variable and use that variable.

Which is best and why?

12条回答
在下西门庆
2楼-- · 2019-03-15 06:15

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...

查看更多
Emotional °昔
3楼-- · 2019-03-15 06:16

This is something that you, as the API writer, have to indicate to the caller.

In general, if you are simply returning a property, you can mark the call as a final (if you are not offering an actual interface). That should reduce the costs of calls since the compiler would be more likely to inline the function.

If the cost of calculating the property is expensive (E.g., a string lookup), document it in the JAvaDocs for that method, and indicate to the caller that they may want to obtain the value once and cache it.

查看更多
啃猪蹄的小仙女
4楼-- · 2019-03-15 06:17

i think you will see no difference at runtime - assuming you do not create more than one Age class.

查看更多
三岁会撩人
5楼-- · 2019-03-15 06:23

I'll try to say with code examples what the other answer already said.

In the case you presented the call for getAge() is very very simple, and the cost of calling it is almost nothing. Don't bother with it in this case.

But if your getAge was something fancy that do lots of calculations or access IO resources, like:

public int getAge() {
   return slowService.calculateAgeByBirthDate(birthDate); // it takes 2 seconds to execute for every call
}

Then for sure it would be a good idea to cache de result and use it. Because if you call it 30 times your code will take 1 minute to complete.

查看更多
男人必须洒脱
6楼-- · 2019-03-15 06:24

Don't bother. It's absolutely not worth micro-optimizing like this. Wait until you finish your code, then it runs too slowly, then get out a profiler and work on what the profiler tells you is the source of the problem.

Premature optimization is the root of all evil.

查看更多
聊天终结者
7楼-- · 2019-03-15 06:31

Depending on how your application is designed, the two options might actually give different results! If the age instance you're using is shared and mutable, different places in your application might change its value in between your calls to getAge(). In this case, it's a matter of correctness to decide which is the best option for your code, and it's up to you to decide. As the old adage says: "first make it right, then make it fast". And, as others have already mentioned, you probably won't need to worry about the "make it fast" part in this case.

A related example is when you're changing a collection while iterating through it. You have to iterate over a snapshot to not get a ConcurrentModificationException.

查看更多
登录 后发表回答