I have function that generates numbers and stores them to List<int>
.
Now I must store those results into files as fast as possible.
Here is my code so far:
private void Save_Click(object sender, EventArgs e)
{
//this is just for tests
List<int> myResults = Enumerable.Range(1, 50000000).ToList();
const string dir = @"D:\TESTS";
int fileCount = 1;
var file = Path.Combine(dir, string.Format("{0}.csv", fileCount));
var sw = new StreamWriter(file, false);
int i = 0;
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
foreach (int res in myResults.Shuffle())
{
sw.WriteLine(res);
i++;
if (i%200000 != 0) continue;
fileCount++;
sw.Close();
file = Path.Combine(dir, string.Format("{0}.csv", fileCount));
sw = new StreamWriter(file, false);
}
sw.Close();
stopwatch.Stop();
label3.Text = string.Format("Save time(s): {0:0.##}", stopwatch.Elapsed.TotalSeconds);
}
Shuffle is extension method taken from this answer.
public static class Extensions
{
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, Random rng = null)
{
if (rng == null)
rng = new Random();
T[] elements = source.ToArray();
for (int i = elements.Length - 1; i > 0; i--)
{
int swapIndex = rng.Next(i + 1);
yield return elements[swapIndex];
elements[swapIndex] = elements[i];
}
yield return elements[0];
}
}
My problem is that save takes about 5-7 minutes on my PC and when I increase number of results to 100 millions I get OutOfMemoryException
.
How can I speed thing up and eliminate that error?