【发布时间】:2009-09-22 18:28:58
【问题描述】:
我需要将一些信息作为 lambda 表达式传递给某些方法。基本上,这是一种向数据库查询添加信息的方法。一个简单的例子是:
companyData.GetAll(
where => "SomeField = @SOMEFIELD",
order => "Id",
SOMEFIELD => new Parameter {DbType = DbType.String, Value = "some value"}
)
它工作得很好,除了我需要调用LambdaExpression.Compile 来获取参数对象,这对性能影响很大。
为了获得更快的结果,我提供了这个简单的缓存测试:
class ExpressionCache<T,U>
{
private static ExpressionCache<T, U> instance;
public static ExpressionCache<T, U> Instance
{
get
{
if (instance == null) {
instance = new ExpressionCache<T, U>();
}
return instance;
}
}
private ExpressionCache() { }
private Dictionary<string, Func<T, U>> cache = new Dictionary<string, Func<T, U>>();
public Func<T, U> Get(Expression<Func<T, U>> expression)
{
string key = expression.Body.ToString();
Func<T,U> func;
if (cache.TryGetValue(key, out func)) {
return func;
}
func = expression.Compile();
cache.Add(key, func);
return func;
}
}
这个类有很大的不同:从 10000 次迭代的大约 35000 毫秒到大约 700 毫秒。
现在问题来了:使用表达式主体作为字典的键我会遇到什么样的问题?
【问题讨论】:
标签: c# performance lambda