How to read very large text files fast
Question
Does anyone know the fastest way to read large text files (10Mb) into a string.Readln is just too slow.
Answer 1
You may try this:
function R(const FileName: string): string; var M: TFileStream; begin M := TFileStream.Create(FileName, fmOpenRead); try SetLength(Result, M.Size); M.Read(Result[1], M.Size); finally M.Free; end; end;
Answer 2
As an alternative to Christian's suggestion, you can also use a memory-mapped file:
function MMFileToString(const AFilename: string): string; var hFile: THandle; hFileMap: THandle; hiSize: DWORD; loSize: DWORD; text: string; view: pointer; begin Result := ''; if AFilename = '' then Exit; if not FileExists(AFilename) then Exit; {Open the file} hFile := CreateFile( PChar(AFilename), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0 ); if hFile <> INVALID_HANDLE_VALUE then begin loSize := GetFileSize(hFile, @hiSize); {File was opened successfully, now map it:} hFileMap := CreateFileMapping( hFile, nil, PAGE_READONLY, hiSize, loSize, 'TextForString' ); if (hFileMap <> 0) then begin if (GetLastError() = ERROR_ALREADY_EXISTS) then begin MessageDlg( 'Mapping already exists - not created.', mtWarning, [mbOk], 0 ); CloseHandle(hFileMap) end else begin try {File mapped successfully, now map a view of the file into the address space:} view := MapViewOfFile(hFileMap, FILE_MAP_READ, 0, 0, 0); if (view <> nil) then begin {View mapped successfully} {Close file handle - as long is view is open it will persist} CloseHandle(hFile); SetLength(Result, loSize); Move(view^, Result[1], loSize); end else MessageDlg( 'Unable to map view of file. ' + SysErrorMessage(GetLastError), mtWarning, [mbOk], 0 ); finally UnmapViewOfFile(view); {Close view} CloseHandle(hFileMap); {Close mapping} end end end else begin MessageDlg( 'Unable to create file mapping. ' + SysErrorMessage(GetLastError), mtWarning, [mbOk], 0 ); end; end else begin MessageDlg( 'Unable to open file. ' + SysErrorMessage(GetLastError), mtWarning, [mbOk], 0 ); end; end;
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本