我正在编写一个程序来扫描文本文件中的字符串(行)块,并在找到时将块输出到文件中 在我的进程类中,函数proc()需要花费非常长的时间来处理6MB的文件。在我之前编写的一个程序中,我只扫描了一个特定类型的字符串文本,处理同一个文件花了5秒钟。现在我重新编写它以扫描不同字符串的存在。它花了8分多钟,这是一个显着的差异。有没有人有任何想法如何优化这个功能?
这是我的RegEx
System.Text.RegularExpressions.Regex RegExp { get { return new System.Text.RegularExpressions.Regex(@"(?s)(?-m)MSH.+?(?=[\r\n]([^A-Z0-9]|.{1,2}[^A-Z0-9])|$)", System.Text.RegularExpressions.RegexOptions.Compiled); } }
public static class TypeFactory
{
public static List<IMessageType> GetTypeList()
{
List<IMessageType> types = new List<IMessageType>();
types.AddRange(from assembly in AppDomain.CurrentDomain.GetAssemblies()
from t in assembly.GetTypes()
where t.IsClass && t.GetInterfaces().Contains(typeof(IMessageType))
select Activator.CreateInstance(t) as IMessageType);
return types;
}
}
public class process
{
public void proc()
{
IOHandler.Read reader = new IOHandler.Read(new string[1] { @"C:\TEMP\DeIdentified\DId_RSLTXMIT.LOG" });
List<IMessageType> types = MessageType.TypeFactory.GetTypeList();
//TEST1
IOHandler.Write.writeReport(System.DateTime.Now.ToString(), "TEST", "v3test.txt", true);
foreach (string file in reader.FileList)
{
using (FileStream readStream = new FileStream(file, FileMode.Open, FileAccess.Read))
{
int charVal = 0;
Int64 position = 0;
StringBuilder fileFragment = new StringBuilder();
string message = string.Empty;
string current = string.Empty;
string previous = string.Empty;
int currentLength = 0;
int previousLength = 0;
bool found = false;
do
{
//string line = reader.ReturnLine(readStream, out charVal, ref position);
string line = reader.ReturnLine(readStream, out charVal);
for (int i = 0; i < types.Count; i++)
{
if (Regex.IsMatch(line, types[i].BeginIndicator)) //found first line of a message type
{
found = true;
message += line;
do
{
previousLength = types[i].RegExp.Match(message).Length;
//keep adding lines until match length stops growing
//message += reader.ReturnLine(readStream, out charVal, ref position);
message += reader.ReturnLine(readStream, out charVal);
currentLength = types[i].RegExp.Match(message).Length;
if (currentLength == previousLength)
{
//stop - message complete
IOHandler.Write.writeReport(message, "TEST", "v3test.txt", true);
//reset
message = string.Empty;
currentLength = 0;
previousLength = 0;
break;
}
} while (charVal != -1);
break;
}
}
} while (charVal != -1);
//END OF FILE CONDITION
if (charVal == -1)
{
}
}
}
IOHandler.Write.writeReport(System.DateTime.Now.ToString(), "TEST", "v3test.txt", true);
}
}
编辑:我在VS2012中运行了分析向导,我发现大部分时间花在RegEx.Match函数上
答案 0 :(得分:4)
以下是一些想法:
答案 1 :(得分:0)
高层次的想法:
使用Regex.Matches一次查找所有匹配项,而不是逐个查找。可能是主要的表现
预先构建搜索模式以一次包含多条消息。您可以使用Regex OR。