1

I'm using this code to save/write a plain-text file:

var
  i: int64;
  myFile : TextFile;
  bytes: int64;
begin
  AssignFile(myFile, FileName);
  ReWrite(myFile);
  CloseFile(myFile);

  Append(myFile);    
  bytes:=1073741824; // 1GB
  i:=1;
  while (i<=bytes) do
  begin
    write(myFile, 'a');
    inc(i);
  end;
  CloseFile(myFile);
end;

It perfectly creates the test file. However it takes a lot of time. It may be acceptable for HDD drives but it is very slow for NVMe SSD drives.

How can I make this code faster?

Xel Naga
  • 826
  • 11
  • 28
  • 1
    Writing one character at a time will be painfully slow, as you've discovered. We can only guess that you don't actually need a 1GB file filled with the letter 'a', so what is the actual problem you're trying to solve? There's no "one way" to do this - there will be many options whose suitability will depend on the actual workflow you're trying to implement. – J... Nov 16 '21 at 18:19
  • 1
    Consider this `outStr := StringOfChar('a', bytes div 2); write(myFile, outStr); write(myFile, outStr);`. This completes for me in 18 seconds (10850K, NVMe SSD) because the data is written out in two contiguous blocks instead of one billion individual writes. A single string can't hold a billion characters but it can hold half that - in any case, the point is that organizing your data in memory **before** you write to disk will save you a lot of time over writing the data out one char at a time. – J... Nov 16 '21 at 18:30
  • 1
    Also, ditch the legacy file I/O functions - those are ancient and are also killing your performance. The same strategy as above takes only 3 seconds when using a [TFileStream and a TStreamWriter](https://stackoverflow.com/q/13306752/327083). – J... Nov 16 '21 at 18:39
  • @J... Wow, it is 50 times faster now. Thank you! – Xel Naga Nov 16 '21 at 19:27

0 Answers0