Here is the code:
using (var context = new AventureWorksDataContext())
{
IEnumerable<Customer> _customerQuery = from c in context.Customers
where c.FirstName.StartsWith("A")
select c;
var watch = new Stopwatch();
watch.Start();
var result = Parallel.ForEach(_customerQuery, c => Console.WriteLine(c.FirstName));
watch.Stop();
Debug.WriteLine(watch.ElapsedMilliseconds);
watch = new Stopwatch();
watch.Start();
foreach (var customer in _customerQuery)
{
Console.WriteLine(customer.FirstName);
}
watch.Stop();
Debug.WriteLine(watch.ElapsedMilliseconds);
}
The problem is, Parallel.ForEach
takes about 400ms vs a regular foreach
, which takes about 40ms. What exactly am I doing wrong and why doesn't this work as I expect it to?
Console.WriteLine()
makes it totally irrelevant. – Henk HoltermanConsole.WriteLine()
and replace it withc.FirstName = c.FirstName.ToLowerInvariant()
. You will not see a difference if your collection has around 5000 items; but if your collection has 6000, 7000,... 10.000 items, on a 4 cores processor, you will see a big difference (Parallel.Foreach
will be faster) – Junior Mayhé