When is it more efficient to store the value of a calculation than perform that calculation 2 or more times?

I have always been under the impression that performing a simple arithmetic calculation two or three times is faster than instantiating a variable to hold the value of the calculation.
But, I'm not really sure where I got that notion from.

So, I was wondering if there was a good general guideline to follow?

Recommended Answers

All 8 Replies

The general guideline is to write the code in the clearest, most effective way and worry about optimization only if poor overall performance and code profiling warrant changing it.

That said, if you're using the result of a calculation more than once you should probably store it into a variable for consistency and clarity. If that calculation needs to be performed more than one or two times or in different contexts, move it into a method of it's own.

So, readability aside, it is more efficient to do a fairly simple calculation two or three times than to store the result?

The code in question is going to be called every time the paintComponent method is called on a particular JPanel. So far, it refreshes instantaneously. However, I still have a lot of code to add, and I would like to keep things as efficient as possible, even at the loss of readability.

What do think? Is it more effecient to smithy a new knife every time you need one, or to use the same one again?

But pay attention to what you've already been told. The reusabilty and definately maintenance of the code should be the first priority. Usually, with today's processors, you don't have to worry about effeciency hardly at all (but only hardly, let's not get carried away, here), unless your doing simulations or something to that effect.

So, readability aside, it is more efficient to do a fairly simple calculation two or three times than to store the result?

No, in all likelihood it is not, though allocating such variables in loops can lead to excess GC activity - and even in that case there is a good chance the JIT compiler will re-use a single reference instead of creating a new one each time anyway unless subsequent assignments make that impossible. The short answer is store the calculation in a local variable.

The code in question is going to be called every time the paintComponent method is called on a particular JPanel. So far, it refreshes instantaneously. However, I still have a lot of code to add, and I would like to keep things as efficient as possible, even at the loss of readability.

This is premature optimization at the level you are examining it. The best guideline for tuning painting code is to try to minimize the calculations needed to render. Repaints can occur for many events besides the ones that you are generating in your own code. Updating the variables, either primitives or objects, in the methods that alter them (such as a mouse listener, animation loop, button listener, etc) and letting paint code use those variables is your best choice.

Finishing the code to work correctly with a clean and clear design is much more important at your current stage than worrying about milliseconds of optimization. If you find you do need to improve performance after it is working correctly, profilers can identify the areas to focus on instead of relying on intellectual guesswork on your part.

No, in all likelihood it is not, though allocating such variables in loops can lead to excess GC activity - and even in that case there is a good chance the JIT compiler will re-use a single reference instead of creating a new one each time anyway unless subsequent assignments make that impossible. The short answer is store the calculation in a local variable.

Actually, the space for the variables is allocated at the "method" level. So, declaring a variable before the loop, or in the loop, has no additional effect what-so-ever. ;-)


Edit: Doing an operation (of any kind) is always more expensive than simply accessing a variable, but, unless it is a very involved calculation, the difference is not enough to be noticed, unless it is being carried out millions or billions of times (such as in simulations, as I already said).

Actually, the space for the variables is allocated at the "method" level. So, declaring a variable before the loop, or in the loop, has no additional effect what-so-ever. ;-)

The part that I haven't found a definitive answer on is whether that space is re-initialized if the declaration is within the loop. Many older tips on tuning recommend declaring the variable before the loop rather than inside it, but I think more recent compilers will make that optimization on their own. Out of habit, I usually declare such variables just prior to the loop regardless.

Too late to edit the previous. You're right, it makes no difference for primitives :)
I never worried about it enough with primitives to get a "final answer".

Alright, the combination of those posts resulted in a pretty comprehensive answer. It even answered another question I had on the effects of instantiating within a loop opposed to before it. So, thanks for that you guys.

And I know it sounded as if I was throwing readability to the wind, but I had previously written a custom paintComponent method that resulted in a near full second refresh time under certain conditions. I'm sure this was due to my slopping coding, but I've been trying to be very careful since then.
Although I suppose there is a lot more to efficient coding than what I've asked.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.