Created
October 4, 2011 16:00
-
-
Save bltavares/1262019 to your computer and use it in GitHub Desktop.
C# Memmoizer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Memoizer | |
{ | |
class Example | |
{ | |
Memoizer Memoizer = new Memoizer(); | |
bool AlwaysTrue() | |
{ | |
return Memoizer.Memoize("AlwaysTrue", () => true); | |
} | |
ExpensiveObject GetFromGithub(string hash, int time) | |
{ | |
return Memoizer.Memoize("GetFromFacebook", () => (new GitHubber()).ReallyExpensiveMethod() ); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Memoizer | |
{ | |
/// <summary> | |
/// Store a value so you don't run it twice | |
/// </summary> | |
public class Memoizer | |
{ | |
private IDictionary<string, object> _frozenValues = new Dictionary<string, object>(); | |
/// <summary> | |
/// Store a value so you don't run it twice | |
/// </summary> | |
/// <typeparam name="U">The type returned by the function</typeparam> | |
/// <param name="name">The name to be persisted. Can't already exist.</param> | |
/// <param name="lambda">The function to be used.</param> | |
/// <returns>The value of the lambda.</returns> | |
public U Memoize<U>(string name, Func<U> lambda = null) | |
{ | |
if (!_frozenValues.ContainsKey(name)) | |
{ | |
if (lambda == null) | |
return default(U); | |
_frozenValues.Add(name, lambda.Invoke()); | |
} | |
return (U)_frozenValues[name]; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment