ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

Memoize<T, TResult>

Memoize afunction

Source

public static Func<T, TResult> Memoize<T, TResult>(this Func<T, TResult> func)
{
    var t = new Dictionary<T, TResult>();
    return n =>
    {
        if (t.ContainsKey(n)) return t[n];
        else
        {
            var result = func(n);
            t.Add(n, result);
            return result;
        }
    };
}

Example

Func<string, string> format = new Func<string, string>(s =>
{
    // a long running operation
    System.Threading.Thread.Sleep(2000);
    return String.Format("hello {0}", s);
}).Memoize();
// takes 2000 ms
foreach (var item in Enumerable.Range(0, 100))
{
    Response.WriteLine(format(" world"));
}

Author: P.Revington

Submitted on: 26 apr. 2010

Language: C#

Type: System.Func

Views: 8525