Reputation: 204
I have a list of elements and I want to filter the elements into otherlist based on specific condition. I have two options for that:
Use foreach() statement
List<Address> allAddress = new List<Address>();
List<Address> chaplinAddress = new List<Address>();
foreach (Address item in allAddress)
{
if (item.city.ToUpper() == "CHAPLIN")
{
chaplinAddress.Add(item);
}
}
Using Where() clause
List<Address> allAddress = new List<Address>();
List<Address> chaplinAddress = new List<Address>();
chaplinAddress = allAddress.Where(p => p.city.ToUpper() == "CHAPLIN").ToList();
Which of the above method is better for performance?
I looked for how Where() is executed on the below link but I am still not clear on that:
http://msdn.microsoft.com/en-us/library/bb534803.aspx
Upvotes: 0
Views: 107
Reputation: 1149
Decided to test this out. 1,000,000,000 random strings, with one "CHAPLIN" inserted.
Looks like foreach is faster.
Edit: did a more scientific study. Ran each test 1000 times, outside of VS, in release mode.
Keep in mind a tick is one ten-millionth of a second, which makes the difference 0.0000004 seconds, for 1000 lookups of 1,000,000,000 cities.
I think you're good man.
Upvotes: 2
Reputation: 125660
LINQ uses loops internally anyway... You can check how it works internally using .NET Reference Source:
Enumerable.Where
public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) {
if (source == null) throw Error.ArgumentNull("source");
if (predicate == null) throw Error.ArgumentNull("predicate");
if (source is Iterator<TSource>) return ((Iterator<TSource>)source).Where(predicate);
if (source is TSource[]) return new WhereArrayIterator<TSource>((TSource[])source, predicate);
if (source is List<TSource>) return new WhereListIterator<TSource>((List<TSource>)source, predicate);
return new WhereEnumerableIterator<TSource>(source, predicate);
}
Enumerable.ToList
:
public static List<TSource> ToList<TSource>(this IEnumerable<TSource> source) {
if (source == null) throw Error.ArgumentNull("source");
return new List<TSource>(source);
}
and WhereListIterator
(as a link, because it's a little to long to paste here...
There is a little overhead when you use LINQ, because of delegates invocation, but you should not care about that at all. Premature optimization like that is evil, and it's even worse then this tiny little amount of time overhead it requires.
Upvotes: 3
Reputation: 172618
You can use timer object to check which one is faster but generally LINQ are not faster than foreach() as it(LINQ statements) also uses loops internally. On a side note it is to mention that LINQ is much easier to read, understand & lends itself to fewer bugs. But you should not use LINQ if you care much about performance
You may check LINQ vs FOREACH vs FOR Loop Performance
Upvotes: 0