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!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…