C# LINQ Select Vs For loop speed

T.Zacks 3,996 Reputation points
2022-02-04T14:15:26.613+00:00

see the code

LINQ select
List<string> lst = new List<string>();
Stopwatch sw = new Stopwatch();
sw.Start();
IEnumerable<int> squares = Enumerable.Range(0, 1000000).Select(x => x * x);
sw.Stop();
TimeSpan timeSpan1 = sw.Elapsed;
string data = string.Format("{0}h {1}m {2}s {3}ms", timeSpan1.Hours, timeSpan1.Minutes, timeSpan1.Seconds, timeSpan1.Milliseconds);
sw.Reset();

For loop
List<int> m=new List<int>();
sw.Start();
for(int a=0;a<=1000000;a++)
{
m.Add(a * a);
}
sw.Stop();
timeSpan1 = sw.Elapsed;
data = string.Format("{0}h {1}m {2}s {3}ms", timeSpan1.Hours, timeSpan1.Minutes, timeSpan1.Seconds, timeSpan1.Milliseconds);
sw.Reset();

the above LINQ select() taking 3ms where as for loop taking 14ms why for loop getting slower than LINQ select() function ?
Thanks

Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. P a u l 10,761 Reputation points
    2022-02-04T14:32:46.147+00:00

    The result of a .Select() call isn't evaluated until you call a method on it that forces it to be evaluated. In other words, .Select() operations are lazily-evaluated.

    All .Select() does is return an object that holds a reference to the source data, and a function (which you provide to it when you call .Select()) which at some point in your program you can evaluate (for example, by calling .ToList(), .Count() or .Max() on it.

    If you add .ToList() to the end of your first test you'll see the take taken increase.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.