【发布时间】:2010-10-16 19:16:33
【问题描述】:
场景:我需要以数学方式处理超过 1.5GB 的文本和 csv 文件。我尝试使用 SQL Server Express,但加载信息,即使使用 BULK 导入也需要很长时间,理想情况下我需要将整个数据集放在内存中,以减少硬盘 IO。
有超过 120,000,000 条记录,但即使我尝试将信息过滤到仅一列(内存中),我的 C# 控制台应用程序也消耗约 3.5GB 的内存来处理仅 125MB(实际读入 700MB)文本。
GC 似乎没有收集对字符串和字符串数组的引用,即使在将所有引用设置为 null 并使用 using 关键字封装 IDisposables 之后也是如此。
我认为罪魁祸首是 String.Split() 方法,它为每个逗号分隔值创建一个新字符串。
您可能会建议我什至不应该将不需要的*列读入字符串数组,但这没有抓住重点:如何将这个 整个 数据集放在内存中,以便我可以处理它在 C# 中是并行的吗?
我可以优化统计算法并使用复杂的调度算法协调任务,但这是我在遇到内存问题之前希望做的事情,而不是因为。
我已经包含一个完整的控制台应用程序,它可以模拟我的环境,应该有助于重现问题。
感谢任何帮助。提前致谢。
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace InMemProcessingLeak
{
class Program
{
static void Main(string[] args)
{
//Setup Test Environment. Uncomment Once
//15000-20000 files would be more realistic
//InMemoryProcessingLeak.GenerateTestDirectoryFilesAndColumns(3000, 3);
//GC
GC.Collect();
//Demostrate Large Object Memory Allocation Problem (LOMAP)
InMemoryProcessingLeak.SelectColumnFromAllFiles(3000, 2);
}
}
class InMemoryProcessingLeak
{
public static List<string> SelectColumnFromAllFiles(int filesToSelect, int column)
{
List<string> allItems = new List<string>();
int fileCount = filesToSelect;
long fileSize, totalReadSize = 0;
for (int i = 1; i <= fileCount; i++)
{
allItems.AddRange(SelectColumn(i, column, out fileSize));
totalReadSize += fileSize;
Console.Clear();
Console.Out.WriteLine("Reading file {0:00000} of {1}", i, fileCount);
Console.Out.WriteLine("Memory = {0}MB", GC.GetTotalMemory(false) / 1048576);
Console.Out.WriteLine("Total Read = {0}MB", totalReadSize / 1048576);
}
Console.ReadLine();
return allItems;
}
//reads a csv file and returns the values for a selected column
private static List<string> SelectColumn(int fileNumber, int column, out long fileSize)
{
string fileIn;
FileInfo file = new FileInfo(string.Format(@"MemLeakTestFiles/File{0:00000}.txt", fileNumber));
fileSize = file.Length;
using (System.IO.FileStream fs = file.Open(FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(fs))
{
fileIn = sr.ReadToEnd();
}
}
string[] lineDelimiter = { "\n" };
string[] allLines = fileIn.Split(lineDelimiter, StringSplitOptions.None);
List<string> processedColumn = new List<string>();
string current;
for (int i = 0; i < allLines.Length - 1; i++)
{
current = GetColumnFromProcessedRow(allLines[i], column);
processedColumn.Add(current);
}
for (int i = 0; i < lineDelimiter.Length; i++) //GC
{
lineDelimiter[i] = null;
}
lineDelimiter = null;
for (int i = 0; i < allLines.Length; i++) //GC
{
allLines[i] = null;
}
allLines = null;
current = null;
return processedColumn;
}
//returns a row value from the selected comma separated string and column position
private static string GetColumnFromProcessedRow(string line, int columnPosition)
{
string[] entireRow = line.Split(",".ToCharArray());
string currentColumn = entireRow[columnPosition];
//GC
for (int i = 0; i < entireRow.Length; i++)
{
entireRow[i] = null;
}
entireRow = null;
return currentColumn;
}
#region Generators
public static void GenerateTestDirectoryFilesAndColumns(int filesToGenerate, int columnsToGenerate)
{
DirectoryInfo dirInfo = new DirectoryInfo("MemLeakTestFiles");
if (!dirInfo.Exists)
{
dirInfo.Create();
}
Random seed = new Random();
string[] columns = new string[columnsToGenerate];
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= filesToGenerate; i++)
{
int rows = seed.Next(10, 8000);
for (int j = 0; j < rows; j++)
{
sb.Append(GenerateRow(seed, columnsToGenerate));
}
using (TextWriter tw = new StreamWriter(String.Format(@"{0}/File{1:00000}.txt", dirInfo, i)))
{
tw.Write(sb.ToString());
tw.Flush();
}
sb.Remove(0, sb.Length);
Console.Clear();
Console.Out.WriteLine("Generating file {0:00000} of {1}", i, filesToGenerate);
}
}
private static string GenerateString(Random seed)
{
StringBuilder sb = new StringBuilder();
int characters = seed.Next(4, 12);
for (int i = 0; i < characters; i++)
{
sb.Append(Convert.ToChar(Convert.ToInt32(Math.Floor(26 * seed.NextDouble() + 65))));
}
return sb.ToString();
}
private static string GenerateRow(Random seed, int columnsToGenerate)
{
StringBuilder sb = new StringBuilder();
sb.Append(seed.Next());
for (int i = 0; i < columnsToGenerate - 1; i++)
{
sb.Append(",");
sb.Append(GenerateString(seed));
}
sb.Append("\n");
return sb.ToString();
}
#endregion
}
}
*在程序的整个生命周期中,这些其他列将被需要并按顺序和随机访问,因此每次从磁盘读取都是非常繁重的开销。
**环境说明:4GB DDR2 SDRAM 800、Core 2 Duo 2.5Ghz、.NET Runtime 3.5 SP1、Vista 64。
【问题讨论】:
-
除了下面的答案,我注意到您使用了基于数组的 List
。据我所知,每次达到当前容量时,数组大小都会翻倍。因此,一旦达到特定限制,这可能真的很麻烦。
标签: c# performance memory string garbage-collection