50 lines
1.4 KiB
Plaintext
50 lines
1.4 KiB
Plaintext
Because ``++IEnumerable++``s are lazy-evaluated, each iteration causes a re-retrieval of the values, which could involve considerable overhead. For instance, when the ``++IEnumerable++`` is backed by a database, each iteration requires an additional round of database interactions. For that reason, any time the set represented by an ``++IEnumerable++`` must be iterated multiple times, it should first be converted to a ``++List++``, which will retrieve the values and store them in memory. From that point they can be iterated as often as needed without an additional performance hit.
|
|
|
|
|
|
This rule raises an issue for each iteration of an ``++IEnumerable++`` after the first one.
|
|
|
|
|
|
== Noncompliant Code Example
|
|
|
|
[source,csharp]
|
|
----
|
|
IEnumerable<int> numbers = GetNumbers();
|
|
|
|
var count = numbers.Count(); // causes an iteration
|
|
var last = numbers.Last(); // Noncompliant; causes an iteration
|
|
|
|
foreach(var x in numbers) // Noncompliant
|
|
{
|
|
// ...
|
|
}
|
|
----
|
|
|
|
[source,csharp]
|
|
----
|
|
List<int> numbers = GetNumbers().ToList(); // iterable to your heart's content
|
|
|
|
var count = numbers.Count();
|
|
var last = numbers.[count -1];
|
|
|
|
foreach(var x in numbers)
|
|
{
|
|
// ...
|
|
}
|
|
----
|
|
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
include::message.adoc[]
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
include::comments-and-links.adoc[]
|
|
endif::env-github,rspecator-view[]
|