By "immutable function" or "immutable method", I mean a function whose result will never vary if you give it the same arguments.
I would be interested to know if anyone know of a more generic or less verbose solution when you want to cache the precomputed value(s) of an immutable function.
Let me explain what I mean with a simple example:
//Let's assume that ComputeStuff() returns a widely used value
//and that
//1. It is immutable (it will always return the same result)
//2. its performance is critical, and it cannot be accepted to compute
// the result at each call, because the computation is too slow
//I show here a way to solve the problem, based on a cached result.
//(this example works in a case of a method with no arguments.
// A hash would be required in order to store multiple precomputed results
//depending upon the arguments)
private string mComputeStuff_Cached = null;
public string ComputeStuff()
{
if (mComputeStuff_Cached != null)
return mComputeStuff_Cached ;
string result;
//
// ...
//Do lots of cpu intensive computation in order to compute "result"
//or whatever you want to compute
//(for example the hash of a long file)
//...
//
mComputeStuff_Cached = result;
return mComputeStuff_Cached ;
}
Notes:
- I added the tag C++ as a solution in C++ would also interest me
- The concept of "immutable functions" is common for database developers, since a function can be defined as "immutable", or "immutable within a transaction" (this is a good way to improve the performance of the queries).
Thanks in advance