Is a LINQ statement faster than a foreach loop?

I am writing a Mesh Rendering manager and thought it would be nice to group all cells that use the same shader and then render them while I am in this shader passage.

I am currently using the foreach , but wondered if using LINQ can increase performance?

+74
performance c # foreach linq
Jul 01 '10 at 8:18
source share
8 answers

Why will LINQ be faster? It also uses loops inside.

In most cases, LINQ will be a little slower because it introduces overhead. Do not use LINQ if you care about performance. Use LINQ because you need more readable and supported code.

+138
Jul 01 '10 at 8:21
source share

LINQ-to-Objects usually adds some marginal overhead (multiple iterators, etc.). It still needs to do loops and has delegate calls and usually has to do some extra raffles to get the captured variables, etc. In most codes, this will be almost impossible to detect and more than accessible to a simpler understanding of the code.

With other LINQ providers, such as LINQ-to-SQL, then since the query can be filtered on the server, it should be much better than a flat foreach , but most likely you would not make a "select * from foo" blanket in any case, so this is not necessarily a fair comparison.

Re PLINQ; parallelism can shorten elapsed time, but overall processor time tends to increase slightly due to the overhead of threading, etc.

+47
Jul 01 '10 at 8:23
source share

I think LINQ is best used in a foreach because it gives you much cleaner and cleaner code. But LINQ is slower than foreach . To get more, check out the LINQ vs FOREACH vs FOR Loop Performance article.

+14
Jul 01 '10 at 8:20
source share

LINQ is slower, but at some point it may speed up. The good thing about LINQ is that you do not need to care about how this works. If the new method is considered incredibly fast, people at Microsoft can implement it without even telling you, and your code will be much faster.

Moreover, LINQ is much easier to read. That should be enough.

+13
Jul 01 '10 at 8:51
source share

You can improve performance by using parallel LINQs across multiple cores. See Parallel LINQ (PLINQ) (MSDN).

+7
Jul 01 '10 at 8:22
source share

It should probably be noted that the for loop is faster than foreach . Therefore, for the original message, if you are concerned about performance on a critical component, such as a renderer, use a for loop.

Link: In .NET, which loop is faster, 'for' or 'foreach'?

+7
Oct 18 '11 at 13:17
source share

I was interested in this question, so I did the test just now. Using the .NET Framework 4.5.2 on an i3-2328M processor with an Intel (R) Core i3-2328M processor with a frequency of 2.20 GHz, 2200 MHz, 2 cores with 8 GB of RAM running Microsoft Windows 7 Ultimate.

It seems that LINQ may be faster than for each cycle. Here are the results I got:

 Exists=True Time=174 Exists=True Time=149 

It would be interesting if some of you could copy and paste this code into a console application and test it. Before testing with the object (Employee) I tried the same test with integers. LINQ was faster there.

 public class Program { public class Employee { public int id; public string name; public string lastname; public DateTime dateOfBirth; public Employee(int id,string name,string lastname,DateTime dateOfBirth) { this.id = id; this.name = name; this.lastname = lastname; this.dateOfBirth = dateOfBirth; } } public static void Main() { StartObjTest(); } #region object test public static void StartObjTest() { List<Employee> items = new List<Employee>(); for (int i = 0; i < 10000000; i++) { items.Add(new Employee(i,"name" + i,"lastname" + i,DateTime.Today)); } Test3(items, items.Count-100); Test4(items, items.Count - 100); Console.Read(); } public static void Test3(List<Employee> items, int idToCheck) { Stopwatch s = new Stopwatch(); s.Start(); bool exists = false; foreach (var item in items) { if (item.id == idToCheck) { exists = true; break; } } Console.WriteLine("Exists=" + exists); Console.WriteLine("Time=" + s.ElapsedMilliseconds); } public static void Test4(List<Employee> items, int idToCheck) { Stopwatch s = new Stopwatch(); s.Start(); bool exists = items.Exists(e => e.id == idToCheck); Console.WriteLine("Exists=" + exists); Console.WriteLine("Time=" + s.ElapsedMilliseconds); } #endregion #region int test public static void StartIntTest() { List<int> items = new List<int>(); for (int i = 0; i < 10000000; i++) { items.Add(i); } Test1(items, -100); Test2(items, -100); Console.Read(); } public static void Test1(List<int> items,int itemToCheck) { Stopwatch s = new Stopwatch(); s.Start(); bool exists = false; foreach (var item in items) { if (item == itemToCheck) { exists = true; break; } } Console.WriteLine("Exists=" + exists); Console.WriteLine("Time=" + s.ElapsedMilliseconds); } public static void Test2(List<int> items, int itemToCheck) { Stopwatch s = new Stopwatch(); s.Start(); bool exists = items.Contains(itemToCheck); Console.WriteLine("Exists=" + exists); Console.WriteLine("Time=" + s.ElapsedMilliseconds); } #endregion } 
+1
Nov 13 '17 at 11:06
source share

This is a pretty tricky question. Linq makes some things very simple, that if you implement them yourself, you can stumble (for example, linq.Except ()). This is especially true for PLinq, and especially for parallel aggregation implemented by PLinq.

In general, for identical code, linq will be slower due to the overhead of calling a delegate.

If, however, you process a large data set and apply relatively simple calculations to the elements, you will get a huge increase in performance if:

  • You are using an array to store data.
  • You use a for loop to access each element (unlike foreach or linq).

    • Note. When testing, please remember that if you use the same array / list for two consecutive tests, the CPU cache will make the second faster. *
0
Dec 13 '17 at 13:27
source share



All Articles