简体   繁体   中英

Performance of repeated getter calls vs. saving value in a local variable

Is one of the following options better than the other? What are the performance considerations?

class HelloWorld {
    String text = "Hello World";
    public String getText() {
        return this.text;
    }
}

HelloWorld helloWorld = new HelloWorld();

// option A:
for (int i = 0; i < HUGE_NUMBER; i++) System.out.println(helloWorld.getText());

// option B:
String text = helloWorld.getText();
for (int i = 0; i < HUGE_NUMBER; i++) System.out.println(text);

I'm asking specifically about the case where (1) the getter function simply returns a property without performing additional calculations and (2) the property is never changed (there is no need to get a "current" version of it).

The compiler might be smart enough to optimise option A into something similar to option B anyway, so here I assume the compiler does not optimise.

Option A involves many many calls to getText and many many accesses to the text field. Option B calls getText once and accesses the text variable many many times. Therefore, option A will take longer, since calling a method is not instantly. The method has to be added to the call stack, and when it returns, be popped from the stack.

But does this difference in speed matter ? You'd have to check for yourself, using a profiler. When in doubt, use a profiler. If this is actually not causing the performance bottleneck, then changing from option A to B is not gonna help.

If you don't even have a performance problem right now, stop worrying about this. Wait until you do see your code running slowly, then check with a profiler.

In your this situation, I am willing to suggest that, you should think over all the angles here,

Option A - Is directly calling the function getText() while executing System.out.println() , some says this is a bad practice while writing so many lines unless you need to for a simple task. some says it halts the line quickly and do some other stuff and then come back here.

On the other hand Option B - It creates a new variable in the memory and storing the data which is almost consuming in terms of time and memory, but when you are printing the data it is super fast.

I can't really say which is well performed while people has different preferable scenarios on different level of tasks.

Instead I can help you with some info, which will help you while you go in the future : Some Data Loading Concepts

I hope it helps.

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