Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Are simple LINQ queries on an IEnumerable<T> lightweight or heavyweight? How do they compare to writing for or foreach loops by hand? Is there a general guideline for when to prefer LINQ versus manual searching?

For example:

var lowNums =
    from n in numbers
    where n < 5
    select n;

Compared to:

List<int> lowNums = new List<int>();

foreach (int n in numbers)
{
    if (n < 5)
    {
        lowNums.Add(n);
    }
}

I was talking to a coworker about LINQ and he expressed some hesitation about using it. He guessed that there might be a lot going on "behind the scenes" in order to support everything LINQ can do.

Is there a significant performance difference between the above examples? Are there any good resources that talk about LINQ performance on collections? A simple Google search for linq performance turned up some seemingly outdated articles.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
407 views
Welcome To Ask or Share your Answers For Others

1 Answer

The authors of LINQ in Action did some benchmarking with for, foreach, List<T>.FindAll, and LINQ queries that all did the same thing. Depending on how the queries were constructed, LINQ was only about 10% slower. As they put it,

LINQ does not come for free.

LINQ is a complex subject, but depending on what you do with it, it doesn't have to add a lot of overhead. Generally LINQ has been built to rely on deferred execution wherever possible, to save memory and CPU until you actually need it.

However, you have to be aware how the different query operators work, because changing the flow of a query could drastically alter how it's executed. Simple queries as you describe are usually not a problem, but operators like Reverse() and conversion operators can throw some wrenches because they require immediate iteration of the result set. There are often multiple ways to write the same query, and depending on how you construct it, you can be looking at a minimal performance loss or you could make it twice as slow as the equivalent loops.

The convienence and conciseness it offers far outweighs any performance considerations for most of my day to day coding though. Never pre-optimize!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...