我正在将文本文件(.itf)与位于文件夹中的某些逻辑进行合并。当我将它编译为32位(控制台应用程序,.Net 4.6)时,一切正常,但如果文件夹中有大量数据,则会得到outofmemory
异常。将其编译为64位可以解决这个问题,但与32位进程相比,它运行速度非常慢(超过15倍)。用64位进程读取文本文件非常慢
我试过BufferedStream
和ReadAllLines
,但两者表现都很差。分析器告诉我这些方法占用了99%的时间。我不知道是问题是...
下面的代码:
private static void readData(Dictionary<string, Topic> topics)
{
foreach (string file in Directory.EnumerateFiles(Path, "*.itf"))
{
Topic currentTopic = null;
Table currentTable = null;
Object currentObject = null;
using (var fs = File.Open(file, FileMode.Open))
{
using (var bs = new BufferedStream(fs))
{
using (var sr = new StreamReader(bs, Encoding.Default))
{
string line;
while ((line = sr.ReadLine()) != null)
{
if (line.IndexOf("ETOP") > -1)
{
currentTopic = null;
}
else if (line.IndexOf("ETAB") > -1)
{
currentTable = null;
}
else if (line.IndexOf("ELIN") > -1)
{
currentObject = null;
}
else if (line.IndexOf("MTID") > -1)
{
MTID = line.Replace("MTID ", "");
}
else if (line.IndexOf("MODL") > -1)
{
MODL = line.Replace("MODL ", "");
}
else if (line.IndexOf("TOPI") > -1)
{
var name = line.Replace("TOPI ", "");
if (topics.ContainsKey(name))
{
currentTopic = topics[name];
}
else
{
var topic = new Topic(name);
currentTopic = topic;
topics.Add(name, topic);
}
}
else if (line.IndexOf("TABL") > -1)
{
var name = line.Replace("TABL ", "");
if (currentTopic.Tables.ContainsKey(name))
{
currentTable = currentTopic.Tables[name];
}
else
{
var table = new Table(name);
currentTable = table;
currentTopic.Tables.Add(name, table);
}
}
else if (line.IndexOf("OBJE") > -1)
{
if (currentTable.Name != "Metadata" || currentTable.Objects.Count == 0)
{
var shortLine = line.Replace("OBJE ", "");
var obje = new Object(shortLine.Substring(shortLine.IndexOf(" ")));
currentObject = obje;
currentTable.Objects.Add(obje);
}
}
else if (currentTopic != null && currentTable != null && currentObject != null)
{
currentObject.Data.Add(line);
}
}
}
}
}
}
}
那么Profiler所说的ReadAllLines在哪里放慢速度?另外,你的瓶颈很可能是由于'string.IndexOf'。提示:投资创建一个合适的词法分析器/解析器。 – leppie
我想知道是否字符串分配的数量(所有这些调用'.Replace'创建新字符串)是罪魁祸首 - 一个真正的分析器可能会告诉,但我想知道是否一个机制,将整个文件作为流并读取字符没有任何修改/操作行的字符将是更好的解决方案。 –
代码示例显示了“BufferedStream”版本。我也有一个'ReadAllLines'。在32位分析器中确实表示'Replace'和'IndexOf'方法消耗大量时间。不过,我想知道为什么64位版本要慢得多。 – Chris