IEnumerable and Lazy Evaluation

Similar to my last post, this topic was also inspired by our discussions at this month’s Melbourne Patterns Group meeting.  In the meeting, an attendee mentioned that closures also assist in performing lazy evaluation.

Pedram Rezaei wrote an excellent article on lazy evaluation in C#, which helped me better understand lazy evaluation support in C#.  However, a seemingly minor comment from his post also struck me:

As you can see both Where and Select methods also return an instance of a type implementing IEnumerable<string> meaning that they are not executed until an enumerator is created… and its MoveNext method is called…

For some reason, I never realized returning IEnumerable<> meant the closure would not be evaluated until each MoveNext invocation.  Even though I knew that LINQ queries were generally “lazily evaluated”, I had not realized that this was the reason.

In learning this, I should expand on this statement from my last post:

** ToList( ) is only required if you want to maintain the return type as List<Employee>.  Otherwise, it is probably more appropriate to change to IEnumerable<Employee> here.

The referenced code block:

public List<employee> Managers(List<employee> emps)
return emps.Where(e => e.IsManager).ToList();

Although the statement and code above is still acceptable, it will behave in a way that wasn’t obvious to me at the time.  By converting the IEnumerable<> to a List<>, I had changed the implementation from being ‘lazily evaluated’ to being ‘eagerly evaluated’.  This isn’t necessarily a bad thing, but it is important to be aware of the difference (see this article by Sam Allen for more information).


One thought on “IEnumerable and Lazy Evaluation

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s