(Wide)String - storing in TFileStream, Delphi 7. What is the fastest way?

前端 未结 4 1064
[愿得一人]
[愿得一人] 2021-01-02 23:28

I\'m using Delphi7 (non-unicode VCL), I need to store lots of WideStrings inside a TFileStream. I can\'t use TStringStream as the (wide)strings are mixed with binary data, t

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-03 00:14

    There is nothing special about wide strings, to read and write them as fast as possible you need to read and write as much as possible in one go:

    procedure TForm1.Button1Click(Sender: TObject);
    var
      Str: TStream;
      W, W2: WideString;
      L: integer;
    begin
      W := 'foo bar baz';
    
      Str := TFileStream.Create('test.bin', fmCreate);
      try
        // write WideString
        L := Length(W);
        Str.WriteBuffer(L, SizeOf(integer));
        if L > 0 then
          Str.WriteBuffer(W[1], L * SizeOf(WideChar));
    
        Str.Seek(0, soFromBeginning);
        // read back WideString
        Str.ReadBuffer(L, SizeOf(integer));
        if L > 0 then begin
          SetLength(W2, L);
          Str.ReadBuffer(W2[1], L * SizeOf(WideChar));
        end else
          W2 := '';
        Assert(W = W2);
      finally
        Str.Free;
      end;
    end;
    

提交回复
热议问题