The previous answer has nothing to do with reality. I would like an example of confirming the presence of a case where LINQ is faster than normal code. You need to understand that there is nothing free. It is worth even five kopeks to use foreach
instead of the usual for
. If you need to write a certain library with a performance requirement, you must be very careful when using LINQ . Another question is that, as a rule, the advantages of code quality are much more important than a certain performance drop.
int count = 0; //int[] numbers = { 1, 3, 5, 7, 3, 2, 5, 7 }; int N = 100000; int RUN_COUNT = 10000; Random r = new Random(); int[] numbers = Enumerable.Range(1, N).Select((x) => r.Next()).ToArray(); DateTime started = DateTime.Now; for (int i = 0; i < RUN_COUNT; i++) { count = 0; //foreach (int n in numbers) for (int j = 0; j < numbers.Length; j++ ) { if (numbers[j] > 5) //if (n > 5) { count++; } } } DateTime end = DateTime.Now; TimeSpan tspan = end - started; double iteration_time_simple = (double)tspan.TotalMilliseconds / 1000; //--------------------------------------------------------- started = DateTime.Now; for (int i = 0; i < RUN_COUNT; i++) { count = numbers.Count(n => n > 5); } end = DateTime.Now; tspan = end - started; double iteration_time_linq = (double)tspan.TotalMilliseconds / 1000; Console.WriteLine("linq/simple: {0}", iteration_time_linq / iteration_time_simple); Console.WriteLine("simple time: {0} seconds", iteration_time_simple); Console.WriteLine("linq time: {0} seconds", iteration_time_linq);
At the output we get:
linq/simple: 2.612 simple time: 7.8125 seconds linq time: 20.40625 seconds
That is, the variant with LINQ runs more than 2.5 times slower.
My resume: use LINQ , but if necessary, using the profiler, rewrite completely inadequate places; If you write LINQ crazy, you can get a difference of more than 10 times and beyond.