简体   繁体   中英

java - is initializing a temporary variable for simple getters better or not?

A very unimportant question about Java performance, but it made me wondering today.

Say I have simple getter:

public Object getSomething() {
     return this.member;
}

Now, say I need the result of getSomething() twice (or more) in some function/algorithm. My question: is there any difference in either calling getSomething() twice (or more) or in declaring a temporary, local variable and use this variable from then on?

That is, either

public void algo() {
    Object o = getSomething();

    ... use o ...
}

or

public void algo() {
    ... call getSomething() multiple times ...
}

I tend to mix both options, for no specific reason. I know it doesn't matter, but I am just wondering.

Thanks!

Technically, it's faster to not call the method multiple times, however this might not always be the case. The JVM might optimize the method calls to be inline and you won't see the difference at all. In any case, the difference is negligible.

However, it's probably safer to always use a getter. What if the value of the state changes between your calls? If you want to use a consistent version, then you can save the value from the first call. Otherwise, you probably want to always use the getter.

In any case, you shouldn't base this decision on performance because it's so negligible. I would pick one and stick with it consistently. I would recommend always going through your getters/setters.

Getters and setters are about encapsulation and abstraction. When you decide to invoke the getter multiple times, you are making assumptions about the inner workings of that class . For example that it does no expensive calculations, or that the value is not changed by other threads.

I'd argue that its better to call the getter once and store its result in a temporary variable, thus allowing you to freely refactor the implementing class.

As an anecdote, I was once bitten by a change where a getter returned an array, but the implementing class was changed from an array property to using a list and doing the conversion in the getter.

编译器应将其中任一优化为基本相同的代码。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM