K
kndg
Dear all,
If I have a data sequence that is computationally expensensive, what is
your recommended strategy for data caching? My current approach would be
as below sample code, so any subsequent call to foreach statement would
be as fast as possible. Is this a good approach? Or is .Net already have
a build-in class for this purpose?
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
public class TestSequenceCaching : IEnumerable<int>
{
private const int MAX_DATA = 10;
private readonly List<int> dataCache = new List<int>(MAX_DATA);
public int Length
{
get { return MAX_DATA; }
}
public int this[int index]
{
get
{
if (index < 0 || index >= MAX_DATA) throw new
IndexOutOfRangeException();
if (index >= dataCache.Count)
{
var enumerator = GetEnumerator();
while (enumerator.MoveNext() && dataCache.Count <= index) { }
return enumerator.Current;
}
return dataCache[index];
}
}
public IEnumerator<int> GetEnumerator()
{
for (int i = 0; i < MAX_DATA; i++)
{
if (dataCache.Count <= i)
{
int result = GetData(i);
dataCache.Add(result);
yield return result;
}
else
{
yield return dataCache;
}
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
private static int GetData(int i)
{
Thread.Sleep(2000); // simulate expensive computation
return i; // just return back the input for illustration purpose
}
}
Regards.
If I have a data sequence that is computationally expensensive, what is
your recommended strategy for data caching? My current approach would be
as below sample code, so any subsequent call to foreach statement would
be as fast as possible. Is this a good approach? Or is .Net already have
a build-in class for this purpose?
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
public class TestSequenceCaching : IEnumerable<int>
{
private const int MAX_DATA = 10;
private readonly List<int> dataCache = new List<int>(MAX_DATA);
public int Length
{
get { return MAX_DATA; }
}
public int this[int index]
{
get
{
if (index < 0 || index >= MAX_DATA) throw new
IndexOutOfRangeException();
if (index >= dataCache.Count)
{
var enumerator = GetEnumerator();
while (enumerator.MoveNext() && dataCache.Count <= index) { }
return enumerator.Current;
}
return dataCache[index];
}
}
public IEnumerator<int> GetEnumerator()
{
for (int i = 0; i < MAX_DATA; i++)
{
if (dataCache.Count <= i)
{
int result = GetData(i);
dataCache.Add(result);
yield return result;
}
else
{
yield return dataCache;
}
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
private static int GetData(int i)
{
Thread.Sleep(2000); // simulate expensive computation
return i; // just return back the input for illustration purpose
}
}
Regards.