Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
398 views
in Technique[技术] by (71.8m points)

.net - Do LINQ queries have a lot of overhead?

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

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

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...