Information Technology Reference
In-Depth Information
Inverted enumeration uses less memory than the Stop and Go method.
Also, it enables parallel actions on your results. Notice that you still need
to use AsParallel() in your query in order to use ForAll(). ForAll() has a
lower memory footprint than the Stop and Go model. In some situations,
depending on the amount of work being done by the action on the result
of the query expression, inverted enumeration may often be the fastest
enumeration method.
All LINQ queries are executed lazily. You create queries, and those queries
are only executed when you ask for the items produced by the query. LINQ
to Objects goes a step further. LINQ to Objects executes the query on each
item as you ask for that item. PLINQ works differently. Its model is closer
to LINQ to SQL, or the Entity Framework. In those models, when you ask
for the first item, the entire result sequence is generated. PLINQ is closer
to that model, but it's not exactly right. If you misunderstand how PLINQ
executes queries, then you'll use more resources than necessary, and you
can actually make parallel queries run more slowly than LINQ to Objects
queries on multicore machines.
To d e m o n s t r a t e s o m e o f t h e d i f f e r e n c e s , I ' l l w a l k t h r o u g h a r e a s o n a b l y
simple query. I'll show you how adding AsParallel() changes the execution
model. Both models are valid. The rules for LINQ focus on what the results
are, not how they are generated. You'll see that both models will generate
the exact same results. Differences in how would only manifest themselves
if your algorithm has side effects in the query clauses.
Here's the query I used to demonstrate the differences:
var answers = from n in Enumerable .Range(0, 300)
where n.SomeTest()
select n.SomeProjection();
I instrumented the SomeTest() and SomeProjection() methods to show
when each gets called:
public static bool SomeTest( this int inputValue)
{
Console .WriteLine( "testing element: {0}" , inputValue);
return inputValue % 10 == 0 ;
}
public static string SomeProjection( this int input)
{
 
Search WWH ::




Custom Search