通过“不可变函数”或“不可变方法”,我的意思是一个函数,如果你给它相同的参数,它的结果永远不会改变。
当您想缓存不可变函数的预计算值时,我很想知道是否有人知道更通用或更简洁的解决方案。
让我用一个简单的例子来解释我的意思:
//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 ;
}
注意:
- 我添加了标签 C++ 作为 C++ 中的解决方案,我也会感兴趣
- “不可变函数”的概念对于数据库开发人员来说很常见,因为函数可以定义为“不可变”或“在事务中不可变”(这是提高查询性能的好方法)。
提前致谢