Difference between revisions of "TBufStream"

From Lazarus wiki
Jump to navigationJump to search
Line 8: Line 8:
  
 
<syntaxhighlight lang="pascal">var
 
<syntaxhighlight lang="pascal">var
    WBufStream : TWriteBufStream;
+
  WBufStream: TWriteBufStream;
    FileStream : TFileStream;  
+
  FileStream: TFileStream;  
 
 
 
begin
 
begin
    ....
+
  ....
    FileStream := TFileStream.Create('somefile.text', fmCreate);
+
  FileStream := TFileStream.Create('somefile.text', fmCreate);
    WBufStream := TWriteBufStream.Create(FileStream);
+
  WBufStream := TWriteBufStream.Create(FileStream);
    StringList.SaveToStream(WBufStream);
+
  StringList.SaveToStream(WBufStream);
    WBufStream.Free;
+
  WBufStream.Free;
    FileStream.Free;</syntaxhighlight>
+
  FileStream.Free;
 +
</syntaxhighlight>
  
 
In use, the WBufStream will accept and store strings from the StringList, one by one, until its buffer is full (default 16k), it then uses the FileStream to write that content to disk, emptying its own buffer and starts again.
 
In use, the WBufStream will accept and store strings from the StringList, one by one, until its buffer is full (default 16k), it then uses the FileStream to write that content to disk, emptying its own buffer and starts again.

Revision as of 11:23, 2 July 2021

TBufStream

TBufStream is the common ancestor for the TReadBufStream and TWriteBufStream streams. It completely handles the buffer memory management and position management. An instance of TBufStream should never be created directly. It also keeps the instance of the source stream.

TReadBufStream and TWriteBufStream can be used to speed up (or reduce memory consumption) of I/O processes where your application is reading or writing small 'lumps' of data and the underlying operating system is far more efficient handling data in sizable 'lumps'.

And example is presented below where a TStringList contained a large number of strings totaling about 100,000 characters was to be saved to disk. Using TWriteBufStream (instead of StringList.SaveToFile) reduced to time required by a factor of four. In this example, the StringList already contains it's data and for clarity try/finally structures have not been used. Your production code should differ ...

var
  WBufStream: TWriteBufStream;
  FileStream: TFileStream; 
begin
  ....
  FileStream := TFileStream.Create('somefile.text', fmCreate);
  WBufStream := TWriteBufStream.Create(FileStream);
  StringList.SaveToStream(WBufStream);
  WBufStream.Free;
  FileStream.Free;

In use, the WBufStream will accept and store strings from the StringList, one by one, until its buffer is full (default 16k), it then uses the FileStream to write that content to disk, emptying its own buffer and starts again.

See Also