是否可以缓存lambda表达式中计算的值?

时间:2008-09-15 20:04:38

标签: c# linq lambda predicate

在以下代码的ContainsIngredients方法中,是否可以缓存 p.Ingredients 值而不是多次显式引用它?这是一个相当简单的例子,我刚刚为了说明目的而编写,但我正在处理的代码引用了 p 内部的值,例如。 p.InnerObject.ExpensiveMethod()。值

编辑: 我正在使用http://www.albahari.com/nutshell/predicatebuilder.html

中的PredicateBuilder
public class IngredientBag
{
    private readonly Dictionary<string, string> _ingredients = new Dictionary<string, string>();

    public void Add(string type, string name)
    {
        _ingredients.Add(type, name);
    }

    public string Get(string type)
    {
        return _ingredients[type];
    }

    public bool Contains(string type)
    {
        return _ingredients.ContainsKey(type);
    }
}

public class Potion
{
    public IngredientBag Ingredients { get; private set;}
    public string Name {get; private set;}        

    public Potion(string name) : this(name, null)
    {

    }

    public Potion(string name, IngredientBag ingredients)
    {
        Name = name;
        Ingredients = ingredients;
    }

    public static Expression<Func<Potion, bool>> 
        ContainsIngredients(string ingredientType, params string[] ingredients)
    {
        var predicate = PredicateBuilder.False<Potion>();
        // Here, I'm accessing p.Ingredients several times in one 
        // expression.  Is there any way to cache this value and
        // reference the cached value in the expression?
        foreach (var ingredient in ingredients)
        {
            var temp = ingredient;
            predicate = predicate.Or (
                p => p.Ingredients != null &&
                p.Ingredients.Contains(ingredientType) &&
                p.Ingredients.Get(ingredientType).Contains(temp));
        }

        return predicate;
    }

}


[STAThread]
static void Main()
{
    var potions = new List<Potion>
    {
        new Potion("Invisibility", new IngredientBag()),
        new Potion("Bonus"),
        new Potion("Speed", new IngredientBag()),
        new Potion("Strength", new IngredientBag()),
        new Potion("Dummy Potion")
    };

    potions[0].Ingredients.Add("solid", "Eye of Newt");
    potions[0].Ingredients.Add("liquid", "Gall of Peacock");
    potions[0].Ingredients.Add("gas", "Breath of Spider");

    potions[2].Ingredients.Add("solid", "Hair of Toad");
    potions[2].Ingredients.Add("gas", "Peacock's anguish");

    potions[3].Ingredients.Add("liquid", "Peacock Sweat");
    potions[3].Ingredients.Add("gas", "Newt's aura");

    var predicate = Potion.ContainsIngredients("solid", "Newt", "Toad")
        .Or(Potion.ContainsIngredients("gas", "Spider", "Scorpion"));

    foreach (var result in 
                from p in potions
                where(predicate).Compile()(p)
                select p)
    {
        Console.WriteLine(result.Name);
    }
}

5 个答案:

答案 0 :(得分:10)

您考虑过Memoization了吗?

基本理念是这样的;如果你有一个昂贵的函数调用,有一个函数将在第一次调用时计算昂贵的值,但之后返回一个缓存的版本。该函数看起来像这样;

static Func<T> Remember<T>(Func<T> GetExpensiveValue)
{
    bool isCached= false;
    T cachedResult = default(T);

    return () =>
    {
        if (!isCached)
        {
            cachedResult = GetExpensiveValue();
            isCached = true;
        }
        return cachedResult;

    };
}

这意味着你可以写这个;

    // here's something that takes ages to calculate
    Func<string> MyExpensiveMethod = () => 
    { 
        System.Threading.Thread.Sleep(5000); 
        return "that took ages!"; 
    };

    // and heres a function call that only calculates it the once.
    Func<string> CachedMethod = Remember(() => MyExpensiveMethod());

    // only the first line takes five seconds; 
    // the second and third calls are instant.
    Console.WriteLine(CachedMethod());
    Console.WriteLine(CachedMethod());
    Console.WriteLine(CachedMethod());

作为一般策略,它可能有所帮助。

答案 1 :(得分:2)

难道你不能简单地在你从lambda调用的单独的静态函数中编写你的布尔表达式 - 将p.Ingredients作为参数传递......

private static bool IsIngredientPresent(IngredientBag i, string ingredientType, string ingredient)
{
    return i != null && i.Contains(ingredientType) && i.Get(ingredientType).Contains(ingredient);
}

public static Expression<Func<Potion, bool>>
                ContainsIngredients(string ingredientType, params string[] ingredients)
{
    var predicate = PredicateBuilder.False<Potion>();
    // Here, I'm accessing p.Ingredients several times in one 
    // expression.  Is there any way to cache this value and
    // reference the cached value in the expression?
    foreach (var ingredient in ingredients)
    {
        var temp = ingredient;
        predicate = predicate.Or(
            p => IsIngredientPresent(p.Ingredients, ingredientType, temp));
    }

    return predicate;
}

答案 2 :(得分:1)

那么,在这种情况下,如果你不能使用Memoization,那你就受到了限制,因为你真的只能将堆栈用作你的缓存:你无法在你的范围内声明一个新的变量。我需要。所有我能想到的(并且我并没有声称它会很漂亮)会做你想要的但保留你需要的可组合性就像......

private static bool TestWith<T>(T cached, Func<T, bool> predicate)
{
    return predicate(cached);
}

public static Expression<Func<Potion, bool>>
                ContainsIngredients(string ingredientType, params string[] ingredients)
{
    var predicate = PredicateBuilder.False<Potion>();
    // Here, I'm accessing p.Ingredients several times in one 
    // expression.  Is there any way to cache this value and
    // reference the cached value in the expression?
    foreach (var ingredient in ingredients)
    {
        var temp = ingredient;
        predicate = predicate.Or (
            p => TestWith(p.Ingredients,
                i => i != null &&
                     i.Contains(ingredientType) &&
                     i.Get(ingredientType).Contains(temp));
    }

    return predicate;
}

你可以将多个TestWith调用的结果组合成一个更复杂的布尔表达式(如果需要) - 每次调用都会缓存适当的昂贵值 - 或者你可以将它们嵌套在作为第二个参数传递的lambdas中来处理你的复杂深层的层次结构。

虽然读取代码会非常困难,因为你可能会在所有TestWith调用中引入更多堆栈转换,但它是否会提高性能取决于你的ExpensiveCall()的价格有多贵。

作为一个注释,原始示例中没有任何内联,正如另一个答案所建议的那样,因为表达式编译器根据我的知识不进行这样的优化级别。

答案 3 :(得分:0)

在这种情况下,我会说不。我假设编译器可以弄清楚它使用p.Ingredients变量3次,并将变量靠近堆栈或寄存器或其使用的任何内容。

答案 4 :(得分:0)

动荡的智力有正确的答案。

我只是想建议您可以从您使用的类型中删除一些空值和异常,以使其更友好地使用它们。

    public class IngredientBag
    {
      private Dictionary<string, string> _ingredients = 
new Dictionary<string, string>();
      public void Add(string type, string name)
      {
        _ingredients[type] = name;
      }
      public string Get(string type)
      {
        return _ingredients.ContainsKey(type) ? _ingredients[type] : null;
      }
      public bool Has(string type, string name)
      {
        return name == null ? false : this.Get(type) == name;
      }
    }

    public Potion(string name) : this(name, new IngredientBag())    {    }

然后,如果您在此结构中有查询参数...

Dictionary<string, List<string>> ingredients;

您可以像这样编写查询。

from p in Potions
where ingredients.Any(i => i.Value.Any(v => p.IngredientBag.Has(i.Key, v))
select p;

PS,为什么只读?