Method Memoize
| Edit this page View SourceMemoize<TSource>(IEnumerable<TSource>, bool)
Creates a sequence that lazily caches the source as it is iterated for the first time, reusing the cache thereafter for future re-iterations. By default, all sequences are cached, whether they are instantiated or lazy.
Declaration
public static IBuffer<TSource> Memoize<TSource>(this IEnumerable<TSource> source, bool forceCache = true)
Parameters
Type | Name | Description |
---|---|---|
IEnumerable<TSource> | source | The source sequence. |
bool | forceCache | Force caching of ICollection<T>s. |
Returns
Type | Description |
---|---|
IBuffer<TSource> | Returns a sequence that corresponds to a cached version of the input sequence. |
Type Parameters
Name | Description |
---|---|
TSource | Type of elements in |
Remarks
The returned IEnumerable<T> will cache items from source
in a thread-safe
manner. The sequence supplied in source
is not expected to be thread-safe but it is
required to be thread-agnostic. The iterator returned by GetEnumerator() is not
thread-safe, and access should be limited to a single thread/task or controlled via external locks.
By default, Memoize<TSource>(IEnumerable<TSource>, bool) will choose the safe option and cache all IEnumerable<T>s. ICollection<T> will use an optimized form using CopyTo(T[], int), while other IEnumerable<T>s will cache iteratively as each element is requested.
However, if forceCache
is set to false, then data in an ICollection<T> will be returned directly and not cached. In most cases, this is safe, but if the
collection is modified in between uses, then different data may be returned for each iteration.
Examples
The following code example demonstrates how to cache a sequence for repeated use using Memoize
.
var count = 0;
var sequence = Enumerable.Range(1, 10)
.Do(_ => count++);
// get leading elements
var result = sequence.Memoize();
Console.WriteLine($"iterations: {count}");
Console.WriteLine(
"[" +
string.Join(", ", result) +
"]");
Console.WriteLine($"iterations: {count}");
Console.WriteLine(
"[" +
string.Join(", ", result) +
"]");
Console.WriteLine($"iterations: {count}");
// This code produces the following output:
// iterations: 0
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
// iterations: 10
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
// iterations: 10
Exceptions
Type | Condition |
---|---|
ArgumentNullException |
|