I have a function that takes a list of Func<bool> each with an attached value. It iterates the list and returns the attached value if a delegate returns true. Some of these delegates call the same function with the same parameters how do I best memoize the result of such calls within the scope of the TryFindValue method?
The return value of the functions may change between calls to TryFindValue, but they will not change while iterating the list. I would like to avoid generating garbage (boxing/unboxing by casting to object for example). Ideally, I would only have to use the space for memoized values in the scope of TryFindValue and not for the entire lifetime of each delegate for example, but I do not know if that is possible.
public class SomeClass { public bool TryFindValue(List<CondValue> list, out int value) { for (int i = 0; i < list.Count; i++) { var condValue = list[i]; if (condValue.cond()) { value = condValue.value; return true; } } value = default(int); return false; } } public class SomeOtherClass { private List<CondValue> list; public SomeOtherClass() { list = new List<CondValue>(); // SomeMethod(3) will be calculated twice list.Add(new CondValue(() => SomeMethod(3) > SomeOtherMethod(), 42)); list.Add(new CondValue(() => SomeMethod(3) < SomeThirdMethod(), 35)); } private float SomeMethod(int value) { // Implementation... (uses some internal or global state) } private int SomeOtherMethod() { // Implementation... (uses some internal or global state) } private int SomeThirdMethod() { // Implementation... (uses some internal or global state) } } public struct CondValue { public Func<bool> cond; public int value; public CondValue(Func<bool> func, int value) { this.func = func; this.value = value; } }