Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is calculating or variable-reading faster?

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.

like image 995
Andreas Hornig Avatar asked Mar 16 '10 12:03

Andreas Hornig


2 Answers

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.

  • The calculation is a adding two numbers together and you only use the result twice.
  • The calculation is a monstrous Physics calculation involving the interaction of 47 separate sub-atomic particles, and you use it in three different places in your code, one of which uses it inside a loop with 314,159,265 iterations.

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.

like image 181
paxdiablo Avatar answered Sep 20 '22 04:09

paxdiablo


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.

like image 43
MJB Avatar answered Sep 20 '22 04:09

MJB