How to benchmark LINQ query?

  • Thread starter Thread starter Siegfried Heintze
  • Start date Start date
S

Siegfried Heintze

I finally figured out how to implement a doubly nested one-to-many query on
the northwind database using LINQ.

Wow! Printing out all the Customers with orders and order details takes 3
minutes on my 3GHz machine!

I noticed that the queries are lazy! Hmmm.. very clever. That is to say, the
select statements are not executed until I traverse the data structure and
print them out.

If I want to compare this with ADO.NET, how do I force the evaluation of the
lazy queries? Right now, I am forcing them with System.out.WriteLine
statements but delay of actually displaying them on the console is poluting
my benchmarks!

Is there a better way to force the evaluation of those otherwise lazy select
statements without the overhead of the WriteLine?

Thanks,
Siegfried



sw.Start();

var customerOrders = from customer in dc.Customers

join order in dc.Orders on customer.CustomerID equals order.CustomerID

join detail in dc.Order_Details on order.OrderID equals detail.OrderID

select new

{

custID = new XAttribute("CustID", customer.CustomerID),

companyName = new XAttribute("CompanyName", customer.CompanyName),

orders = from subOrders in customer.Orders

select new

{

OrderId = subOrders.OrderID,

details = from subDetails in subOrders.Order_Details

select new

{

product = subDetails.Product.ProductName,

quantity = subDetails.Quantity

}

}

};

TimeSpan ts = sw.Elapsed;

outp.Write(String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours,
ts.Minutes, ts.Seconds,

ts.Milliseconds / 10) + " q to quit: "); if (_getch() == (int)'q') return;

foreach(var customerOrder in customerOrders){

outp.WriteLine(customerOrder.companyName);

foreach (var order in customerOrder.orders){

outp.WriteLine(" {0}", order.OrderId);

foreach (var detail in order.details){

outp.WriteLine(" {0}:{1}", detail.quantity, detail.product);

}

}

}
 
Siegfried said:
Is there a better way to force the evaluation of those otherwise lazy select
statements without the overhead of the WriteLine?

Doing e.g.
var list = (from ... select ...).ToList();
should suffice with LINQ to SQL to fetch the data from the data base
server to your client application.
 
Back
Top