Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad practice to calculate a method once and save the result?

I initially took the gung ho approach in Java of deriving everything, minimizing the use of properties and calculating methods on the fly, every time. But for larger datasets I started running into performance issues, and calling the same method multiple times to only calculate the same result seemed redundant and sometimes an exponential drag to performance.

I finally started taking the approach for data-intensive operations of setting my methods to calculate only the first time it is called and save the result for any future returns.

Is this bad practice?

like image 864
tmn Avatar asked Sep 10 '13 03:09

tmn


1 Answers

Is it bad practice to calculate a method once and save the result?

There is no correct general answer to this1. It depends on the circumstances.

  • It (IMO) is bad practice to do this everywhere as a matter of habit. The JIT compiler is capable of various automatic optimizations that make this hand optimization pointless ... or even harmful. (Generally speaking, hand optimizations are not worthwhile unless you have profiled the complete application using realistic input data, and the profiling tells you that you have a performance hotspot at a particular point in the code.)

    If you do this as a matter of habit (i.e. without thinking), you are probably making your code less readable, and possibly making it slower rather than faster. And if you are thinking about it each time you code a method call, that is going to impact on your productivity.

  • It is not bad practice to do this when you have solid reasons to believe that the method call is likely to be expensive. However, consider that your intuition may be wrong, and that it may be better to rely on profiling to tell you where to spend your efforts. (See note above on productivity.)

  • It is good practice to do this if you have determined that performance is a real concern based on application-level benchmarking, AND you have determined by profiling that hand optimization of these calls is warranted.

  • It is necessary if the method has side-effects and you don't want the side-effects to happen twice.

  • It is incorrect if the method has side-effects and you need the side-effects to happen each time.


The other thing to consider through all of is whether this helps or hinders readability ... and whether maintainability is more or less important to your project than performance.


1 ... and the answers that claim there is are over-generalizing and/or being overly dogmatic. Seriously guys, it is NOT that simple.

like image 78
Stephen C Avatar answered Sep 25 '22 13:09

Stephen C