我有一個簡單的場景,我試圖在股票對象列表上測試表達式編譯樹的性能。以下是代碼編譯表達式樹的性能
表達式編譯樹的性能比靜態lambda調用慢5倍。我不確定這是否是表達式編譯樹所期望的標準性能。希望有任何見解。
LambdaExpression();
List<Stock> stocks = new List<Stock>();
for (int ctr = 0; ctr <= 5000000; ctr++)
{
Stock stk1 = new Stock() { Price = ctr, Symbol = "A", CloseDate = DateTime.Now, FaceValue = ctr } ;
stocks.Add(stk1);
}
CompileTimeLamda(a);
DynamicLambda(a);
public static void LambdaExpression()
{
ParameterExpression CS1 = Expression.Parameter(typeof(Stock), "d");
var line1 = Expression.Equal(Expression.Property(CS1, typeof(Stock).GetProperty("Symbol")), Expression.Constant("MSFT", typeof(string)));
var line2 = Expression.GreaterThan(Expression.Property(Expression.Property(CS1, typeof(Stock).GetProperty("CloseDate")),typeof(DateTime).GetProperty("Millisecond")),
Expression.Constant(0, typeof(int)));
var line3 = Expression.GreaterThan(Expression.Property(CS1, typeof(Stock).GetProperty("Price")), Expression.Constant((double)0, typeof(double)));
var line4 = Expression.And(line1,line2);
var line5 = Expression.OrElse(line4, line3);
func = Expression.Lambda<Func<Stock, bool>>(line5, new ParameterExpression[] { CS1 }).Compile();
}
public static void DynamicLambda(List<Stock> stks)
{
Stopwatch watch = new Stopwatch();
watch.Start();
foreach (var d in stks)
{
func(d);
}
watch.Stop();
Console.WriteLine("Dynamic Lambda :" + watch.ElapsedMilliseconds);
}
public static void CompileTimeLamda(List<Stock> stks)
{
Stopwatch watch = new Stopwatch();
watch.Start();
foreach (var d in stks)
{
if (d.Symbol == "MSFT" && d.CloseDate.Millisecond > 0 ||
(d.Price) > 0) ;
}
watch.Stop();
Console.WriteLine("Compile Time Lamda " +watch.ElapsedMilliseconds);
}
檢查編譯後的IL;優化器可能會殺死所有的代碼。 – SLaks 2012-07-26 21:04:36
你實際上並沒有比較2個lambda表達式。第二個是編譯的代碼,即沒有委託。代表很可能是讓它變慢的原因。 – MikeKulls 2012-07-26 21:38:29
你似乎在比較蘋果和橘子。 「編譯時lambda」完全不使用lambda。另外,編譯器可能會優化掉循環,因爲你沒有真正做任何事情(空語句「;」) – 2012-07-26 21:39:37