【发布时间】:2016-07-25 00:27:54
【问题描述】:
我需要尽快打开和读取数千个文件。
我对 13 592 个文件进行了几次测试,发现方法 1 比方法 2 稍快。这些文件通常在 800 字节到 4kB 之间。我想知道是否有什么办法可以让这个 I/O 绑定过程更快?
Method 1:
Run 1: 3:05 (don't know what happened here)
Run 2: 1:55
Run 3: 2:06
Run 4: 2:02
Method 2:
Run 1: 2:04
Run 2: 2:08
Run 3: 2:04
Run 4: 2:12
代码如下:
public class FileOpenerUtil
{
/// <summary>
///
/// </summary>
/// <param name="fullFilePath"></param>
/// <returns></returns>
public static string ReadFileToString(string fullFilePath)
{
while (true)
{
try
{
//Methode 1
using (StreamReader sr = File.OpenText(fullFilePath))
{
string fullMessage = "";
string s;
while ((s = sr.ReadLine()) != null)
{
fullMessage += s + "\n";
}
return RemoveCarriageReturn(fullMessage);
}
//Methode 2
/*using (File.Open(fullFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
Console.WriteLine("Output file {0} ready.", fullFilePath);
string[] lines = File.ReadAllLines(fullFilePath);
//Every new line under the previous line
string fullMessage = lines.Aggregate("", (current, s) => current + s + "\n");
return RemoveCarriageReturn(fullMessage);
//ninject kernel
}*/
//Methode 3
}
catch (FileNotFoundException ex)
{
Console.WriteLine("Output file {0} not yet ready ({1})", fullFilePath, ex.Message);
}
catch (IOException ex)
{
Console.WriteLine("Output file {0} not yet ready ({1})", fullFilePath, ex.Message);
}
catch (UnauthorizedAccessException ex)
{
Console.WriteLine("Output file {0} not yet ready ({1})", fullFilePath, ex.Message);
}
}
}
/// <summary>
/// Verwijdert '\r' in een string sequence
/// </summary>
/// <param name="message">The text that has to be changed</param>
/// <returns>The changed text</returns>
private static string RemoveCarriageReturn(string message)
{
return message.Replace("\r", "");
}
}
我正在阅读的文件是 .HL7 文件,如下所示:
MSH|^~\&|OAZIS||||20150430235954||ADT^A03|23669166|P|2.3||||||ASCII EVN|A03|20150430235954||||201504302359 PID|1||6001144000||LastName^FirstName^^^Mevr.|LastName^FirstName|19600114|F|||GStreetName Number^^City^^PostalCode^B^H||09/3444556^^PH~0476519246echtg^ ^CP||NL|M||28783409^^^^VN|0000000000|60011402843||||||B||||N PD1||||003847^LastName^FirstName||||||||N|||0 PV1|1|O|FDAG^000^053^001^0^2|NULL||FDAG^000^053^001|003847^LastName^FirstName||006813^LastName^FirstName|1900|00||||| |006813^LastName^FirstName|0|28783409^^^^VN|1^20150430|01||||||||||||||1|1||D|||||201504301336|201504302359 OBX|1|CE|KIND_OF_DIS|RCM|1^1 医疗建议 OBX|2|CE|DESTINATION_DIS|RCM|1^1 Terug naar huis
打开文件后,我使用j4jayant's HL7 parser 解析字符串并关闭文件。
【问题讨论】:
-
至于“这里发生了什么”,通常第一次运行总是比后续运行慢(因为抖动?)。尝试切换方法 1 和 2,您可能会发现现在方法 2 的第一次运行会更慢。
-
首先删除(或注释掉)方法 2 中对
Console.WriteLine的调用。写入控制台对性能有显着影响。 -
fullMessage += s + "\n";StringBuilder应该快一点。 -
File.ReadAllText 怎么样?
-
在方法 2 中,这条线似乎没用:
using (File.Open(fullFilePath, FileMode.Open, FileAccess.Read, FileShare.Read)),因为您已经在使用File.ReadAllLines(fullFilePath),它已经在内部这样做了。
标签: c# asp.net-mvc-4 io hl7