I have been wandering about this for some time now. I’m still a beginner, so my programs are simple and require almost no resources. I’m familiar with C++, Java and C#. But in the future things will get more complicated, with more variables and objects and more functions/methods.
In order to change the value of a variable, I can call a function/method, that changes the value, once. After that when I need the variable, I have to simply call it. It takes less time to get the value. If the function does a lot of work, the time that it has consumed will be experienced only once. But the variables require space in the memory and when their quantity gets quite big, this can become a problem.
But I can call a function/method that returns the value I need. I will only need to use variables where necessary, which means- less variables. It’s not a problem if the function/method is short. But some functions/methods must do quite a lot of work before they return the value. This way the program will seem slower for the user.
My question is: memorizing values in variables VS using functions/methods that return the value: which is better, when and why?
This question sounds like: high speed and more consumed memory VS less consumed memory and low speed…
It is usually wise to avoid caching values which can be computed, since then you can avoid having to maintain state in separate places (and breaking consistency if you eventually forget).
It is a good idea to abstract away on the calculation of some value (like hiding it behind a function). Later once your code works and you feel it slow, then use profiling to determine the hotspots. If such a function turns out to be a hotspot, you can introduce caching / memoizing underneath, and the abstraction (in an ideal world) will cover the nasty details from the client (of the function).
Memoization
Memoizing a function usually involves a lookup table (based on array, associative array, etc.) with a key type being the aggregate of the arguments of the memoized function, and the stored value being the return value of the function.
Then, the function would first check if the result is already available in the lookup table and return it, or else compute the result and store it before returning.
In fact, such memoization could be disjoined from the memoized function, and implemented as a separate layer (wrapping the function) if the programming language supports such abstraction. In languages without first-class functions, this can usually be achieved using interfaces and single-method classes.