我正在將文本文件(.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