文本文件在Delphi中编写性能
发布时间:2020-12-15 09:44:00 所属栏目:大数据 来源:网络整理
导读:我的软处理传入的字符串(来自Telnet或HTTP或……),我必须用Delphi XE2编写文本文件,以获得一些处理过的字符串.因为有时字符串可能会崩溃程序我需要确保在我的文件中有字符串.所以我打开/关闭每个传入字符串的文件,我有一些性能问题.通常(对于我的代码测试)为
我的软处理传入的字符串(来自Telnet或HTTP或……),我必须用Delphi XE2编写文本文件,以获得一些处理过的字符串.因为有时字符串可能会崩溃程序我需要确保在我的文件中有字符串.所以我打开/关闭每个传入字符串的文件,我有一些性能问题.通常(对于我的代码测试)为8秒
我的代码在这里,有没有办法改善保持功能的性能? Procedure AddToFile(Source: string; FileName :String); var FText : Text; TmpBuf: array[word] of byte; Begin {$I-} AssignFile(FText,FileName); Append(FText); SetTextBuf(FText,TmpBuf); Writeln(FText,Source); CloseFile(FText); {$I+} end; procedure initF(FileName : string); Var FText : text; begin {$I-} if FileExists(FileName) then DeleteFile(FileName); AssignFile(FText,FileName); ReWrite(FText); CloseFile(FText); {$I+} end; procedure TForm1.Button1Click(Sender: TObject); var tTime : TDateTime; iBcl : Integer; FileName : string; begin FileName := 'c:Test.txt'; lbl1.Caption := 'Go->' + FileName; lbl1.Refresh; initF(FileName); tTime := Now; For iBcl := 0 to 2000 do AddToFile(IntToStr(ibcl) + ' ' + 'lkjlkjlkjlkjlkjlkjlkj',FileName); lbl1.Caption := FormatDateTime('sss:zzz',Now-tTime); end; 解决方法
使用自动缓冲的
TStreamWriter ,可以自动将其缓冲区刷新到TFileStream.如果需要,它还允许您选择附加到现有文件,设置Unicode支持的字符编码,并允许您在其各种重载的
Create 构造函数中设置不同的缓冲区大小(默认值为1024字节或1K).
(请注意,刷新TStreamWriter只会将TStreamBuffer的内容写入TFileStream;它不会刷新OS文件系统缓冲区,因此在释放TFileStream之前,文件实际上不会写入磁盘.) 不要每次都创建StreamWriter;只需创建并打开一次,最后关闭它: function InitLog(const FileName: string): TStreamWriter; begin Result := TStreamWriter.Create(FileName,True); Result.AutoFlush := True; // Flush automatically after write Result.NewLine := sLineBreak; // Use system line breaks end; procedure CloseLog(const StreamWriter: TStreamWriter); begin StreamWriter.Free; end; procedure TForm1.Button1Click(Sender: TObject); var tTime : TDateTime; iBcl : Integer; LogSW: TStreamWriter; FileName: TFileName; begin FileName := 'c:Test.txt'; LogSW := InitLog(FileName); try lbl1.Caption := 'Go->' + FileName; lbl1.Refresh; tTime := Now; For iBcl := 0 to 2000 do LogSW.WriteLine(IntToStr(ibcl) + ' ' + 'lkjlkjlkjlkjlkjlkjlkj'); lbl1.Caption := FormatDateTime('sss:zzz',Now - tTime); finally CloseLog(LogSW); end; end; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |