「不変関数」または「不変メソッド」とは、同じ引数を与えても結果が決して変わらない関数を意味します。
不変関数の事前計算された値をキャッシュしたい場合、より一般的または冗長でない解決策を誰かが知っているかどうか知りたいです。
簡単な例で私が何を意味するかを説明しましょう。
//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++ というタグも追加しました。これも興味があります
- 関数は「不変」または「トランザクション内で不変」と定義できるため、「不変関数」の概念はデータベース開発者にとって一般的です (これは、クエリのパフォーマンスを向上させる良い方法です)。
前もって感謝します