There are two aspects: speed and memory.
The speed aspect becomes more apparent if you use a method like .Take()
to consume only part of the original result set.
Since the first example uses only stream operators before calling Take
, you end up outputting values ββfrom 1 to 10 before Take
stops evaluating. In addition, only one value is loaded into memory at a time, so you have a very small amount of memory.
In the second example, OrderByDescending
not translated, so the Take pull moment of the first element, the entire result that passed through the Where
filter, must be placed in memory for sorting. This can take a lot of time and create a large amount of memory.
Even if you have not used Take
, a memory issue can be important. For instance:
// Puts half a million elements in memory, sorts, then outputs them. var numbers = Enumerable.Range(1, 1000000).Where(i => i % 2 == 0) .OrderByDescending(i => i); foreach(var number in numbers) Console.WriteLine(number); // Puts one element in memory at a time. var numbers = Enumerable.Range(1, 1000000).Where(i => i % 2 == 0); foreach(var number in numbers) Console.WriteLine(number);
source share