Ðаn
Ðаn

Reputation: 10875

What is the expected performance of IEnumerable?

Properties are expected to perform similarly to fields, even though they are really functions. What can be said about the expected performance of an arbitrary IEnumerable?

Is it fair to borrow the concept from properties and say that an IEnumerable should perform about the same as iterating an array or List<T>?

Or, is it okay for just about anything happen with each iteration: database access, web service call, time-consuming computation, etc.

Upvotes: 1

Views: 212

Answers (4)

usr
usr

Reputation: 171178

Speaking from experience you can't really infer anything about the performance of an arbitrary IEnumerable. For example, it might be an IQueryable in disguise, hitting the database every time it is enumerated. Or it might be the result of File.EnumerateLines.

Sometimes it is important that the enumerable only be enumerated once.

This is in contrast to a property. If a property was to hit the database or read I file I'd consider this to be a code smell. For an IEnumerable it is just normal.

Upvotes: 1

herzmeister
herzmeister

Reputation: 11287

An IEnumerable of course can be used to access a database or crawl through a file, but if you expose such an IEnumerable, you should clearly document it doing so.

If it's not immediately clear that it's expensive, you should encapsulate it appropriately, and only expose an in-memory enumeration.

Upvotes: 0

agent-j
agent-j

Reputation: 27923

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

If your object exposes a property that is of type IEnumerable, that is expected to return in constant time, but the enumeration of that enumerator should probably have no expectations.

Of course, your situation may vary. For example, if you are binding some WPF control to that enumerable, your users will want it to return quickly.

Upvotes: 0

Joe Enos
Joe Enos

Reputation: 40403

I'd say there's no rule on how well an IEnumerable<T> should perform - only about how it should behave, which means it should loop through your collection.

If you need to access the database at the beginning of the iteration (like Entity Framework's IQueryable<T>), that's fine - if it needs to make a DB or file call per item, that's fine. The only important thing to me is that you can loop through it.

Upvotes: 1

Related Questions