What is the expected IEnumerable performance?

Properties are expected to execute similarly to fields, even if they are truly functions. What about the expected performance of arbitrary IEnumerable ?

Is it possible to borrow a concept from properties and say that IEnumerable should work in much the same way as iterating an array or List<T> ?

Or, everything is in order, something happens with each iteration: access to the database, calling the web service, time-consuming calculations, etc.

+1
source share
4 answers

From experience, you can't say anything about the performance of arbitrary IEnumerable . For example, it could be a hidden IQueryable , falling into the database every time it is enumerated. Or it could be the result of File.EnumerateLines .

Sometimes itโ€™s important to list only once.

This is different from the property. If the property got into the database or read file I, I would have thought that it was the smell of code. For IEnumerable this is normal.

+1
source

I would say that there is no rule about how well IEnumerable<T> should perform - only about how it should behave, which means that it must go through your collection.

If you need to access the database at the beginning of the iteration (for example, Entity Framework IQueryable<T> ), thatโ€™s fine - if you need to make a DB or file for each item, thatโ€™s fine. The only thing that matters to me is that you can skip it.

+1
source

IEnumerable has no properties, but IEnumerable returns an IEnumerator, as you know.

If your object provides a property that is of type IEnumerable, it is expected that it will return in constant time, but an enumeration of this enumerator should probably have no expectations .

Of course, your situation may change . For example, if you bind some WPF control to this enumerated, your users will want it to return quickly.

0
source

Of course, IEnumerable can be used to access the database or crawl through a file, but if you expose such IEnumerable , you should clearly document it.

If it does not immediately become clear that it is expensive, you should encapsulate it accordingly and only expose the listing in memory.

0
source

All Articles