Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

space complexity of a simple linq(to objects) query

Tags:

c#

linq

I have;

var maxVal = l.TakeWhile(x=>x < val).Where(x=>Matches(x)).Max();

How much space does this need ? Does linq build up a list of the above Where() condition, or is Max() just iterating through the IEnumerable keeping track of what is the current Max() ?

And where can I find more info about this, besides asking on SO f

like image 209
Anonym Avatar asked Aug 08 '10 19:08

Anonym


1 Answers

I have verified with Reflector that each of Enumerable.TakeWhile, Enumerable.Where and Enumerable.Max run in constant space. Consequently, this entire query should run in constant space. Not surprising, considering TakeWhile and Where are speced to use deferred execution + streaming. Max does not use deferred execution, but only needs to store 'max so far' and the enumerator on the source enumerable.

like image 189
Ani Avatar answered Oct 23 '22 14:10

Ani