score:2
I've created a simple test console app.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace LinqPerformance
{
class Program
{
static void Main(string[] args)
{
var data = Enumerable.Range(1, 100000000);
for (int x = 0; x < 10; x++)
{
ExecuteMethods(data);
}
}
private static void ExecuteMethods(IEnumerable<int> data)
{
Method1("linq collection", () =>
{
var collection = data.Where(d => d % 2 == 0);
double count = 0;
foreach (var c in collection)
{
count += c;
}
});
Method1("list collection", () =>
{
var collection = data.Where(d => d % 2 == 0).ToList();
double count = 0;
foreach (var c in collection)
{
count += c;
}
});
Method1("iterable collection", () =>
{
double count = 0;
foreach (var c in data.Where(d => d % 2 == 0))
{
count += c;
}
});
}
private static void Method1(string name, Action body)
{
Stopwatch s = new Stopwatch();
s.Start();
body();
s.Stop();
Console.WriteLine(name + ": " + s.Elapsed);
}
}
}
After running this I can see that the ToList() is the slowest. The other two approaches appear to be the same.
I suppose this is because the foreach is expanded to a
var enumerator = collection.GetEnumerator();
while(enumerator.MoveNext() )
{
var c = enumerator.Current;
count += c;
}
score:0
The performance for both is the same. foreach
will create the IEnumerable(Of T)
then enumerate through it.
However, if you're concerned about performance, try:
Dim collection As IEnumerable(Of Item) _
= CellCollection.Where(Function(i) i.IsPending)
For Each item As Item In collection
'Do something here
Next
It's possible that casting the IEnumerable(Of Item)
to ItemCollection
would cause it to enumerate (like ToArray
or ToList
). This will cause the collection to enumerate twice. Keeping it as IEnumerable
ensures that the i.IsPending
check happens during the enumeration of the For Each
and not the CType()
.
The fastest solution would be to forgo LINQ altogether (LINQ statements, although readable, add some overhead).
For Each item As Item In CellCollection
If Not item.IsPending Then
Continue For
End If
'Do something here
Next
score:1
Performance is the same, whether you assign the Linq query to a variable, or call it directly in the For Each. In both case the iterator will be created once and the For Each loop will go through each item in the list once.
In the first code sample, the CType is not necessary though (actually I don't think it would work). You can simply do:
Dim collection = CellCollection.Where(Function(i) i.IsPending = True)
For Each item As Item In collection
'Do something here
Next
But as I mentioned, assigning to a variable is not necessary. Having the Where clause on the For Each line will yield the same performance, and the code will be shorter and more readable.
Source: stackoverflow.com
Related Query
- Performance and Linq in iterations
- What is the Efficiency and Performance of LINQ and Lambda Expression in .Net?
- LINQ performance Count vs Where and Count
- Performance Difference between LINQ and Stored Procedures
- I am wondering about the state of connection and impact on code performance by 'yield' while iterating over data reader object
- OrderBy and Top in LINQ with good performance
- Hierarchical data in Linq - options and performance
- Enumerable.Empty<T>().AsQueryable(); This method supports the LINQ to Entities infrastructure and is not intended to be used directly from your code
- Linq Intersect bool query and performance
- Linq Count method and Performance
- C# linq order by and other statements with foreach, is there a performance difference?
- LINQ Source Code Available
- Refactor Linq code and "LINQ to Entities does not recognize the method"
- Performance tuning C# permutations and SHA1 code
- How can I code an outer join using LINQ and EF6?
- LINQ Performance with SelectMany, GroupBy and First
- How to perform a LINQ GroupBy, Select, and then Take without performance hit?
- C# - Linq optimize code with List and Where clause
- IEqualityComparer and Linq Distinct - Hard Code GetHashCode()
- Performance and Concept questions in LINQ
- creating Linq to sqlite dbml from DbLinq source code
- Stubbing Code for Test With Linq Expressions and Lambdas
- measure linq to sql performance and stats
- Performance between check exists before add to list and distinct in linq
- Performance difference between `is` and `as` in LINQ
- SQL subquery result in LINQ and Entity Framework Code First
- Poor performance comparing collections of objects using reflections and Linq Except/Intersect
- Performance comparison Sql query and Linq data query
- LINQ to Entities performance issue with Where and Contains
- Code Rewite for tuple and if else statements by using LINQ
More Query from same tag
- LINQ - how to sort by date
- Linq Converting String to List
- Linq query that can use a list of DateTime to filter a List<object>
- How can I fix this LINQ so that it treats a pairs of vals as a distinct value?
- Compare only Date in nHibernate Linq on a DateTime value
- Version of iteration which takes "groups" of elements
- Unable to create a constant value of type ' ' . Only primitive types or enumeration types are supported in this context
- How to get a Child Nodes Attribute
- Need help on Linq-to-SQL query (maybe nested query?)
- How to filter list of dictionary values with criteria
- LINQ - Refactor .Contains comparison on IEnumerable<string> to be case sensitive
- How to validate every value in a List in where Clause?
- How to match the results back to an array
- Generic Interface For Hierarchical Collection
- More elegant way to group DataTable data in structs in C# (using Linq?)
- Looking to pass entity as generic type and extract common functionality
- my api does not return the complete object
- How to Sort a List of Objects by dictionary value?
- Joining results from two queries in C# using LINQ or other module
- moq.As<>().Setup() does not seem to work after getting moq.Object
- How can I use a LINQ statement to filter out items that matches one of the words from another List?
- How to write LINQ query as one query?
- LINQ to get distinct column value with count of a string
- Group method not recognized in LINQ query
- Adding a linked object to another object in C# ASP.Net MVC
- LINQ - How to get Single() review
- Should my DAL return DataTables or I...whatever<>?
- Ensuring a record has all relationships, not any
- LINQ contains appends % and escapes %
- How do I format date literals in dynamic linq?