to be honest, I don't really know what the "small green men" in my cpu and compiler do, so I sometimes would like to know :).
Currently I would like to know what's faster, so that I can design my code in a more efficient way. So for example I want to calclate something at different points in my sourcecode, when will it be faster to calculate it once and store it in a variable that's read and used for the next points it's needed and when is it faster to calculate it everytime?
I think it's depending on how "complex" and "long" the calculation is and how fast then cache is, where variables are stored, but I don't have any clue what's faster :).
Thanks for any reply to my tiny but important question!
Andreas
PS: perhaps it's important to know that I code in JAVA, but it's more a genral question.
It will generally always be faster to store something calculated once, rather than calculate it each time, unless the calculation is minor and/or the number of times you use it is low.
In other words, it depends entirely on the usage patterns. Consider, for example, the two extremes below.
Obviously, you won't get much (or possibly any) benefit from calculating it once in the first example but you're extremely likely to benefit by doing so for the second case.
As a general rule, you should first write your code for functionality and readability, and then only worry about performance if it becomes an issue.
The only time I can think of in which it would automatically be slower is if you stored the value in a file, or in a table (e.g. a database). Then it could be slower to retrieve it than to recalculate it. That does not seem to apply in your case, but you said it was a general question.
But you seem to be dancing around another question -- is it better to use lots of globally stored values. If that is part of your question, then my answer does not address it at all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With