Delphi StringBuilder

后端 未结 7 1729
别那么骄傲
别那么骄傲 2021-02-12 12:26

Exists in Delphi something like the Java or C# StringBuilder? Or Delphi does not need StringBuilder and s := s + \'some string\'; is good expression (mainly in for,

7条回答
  •  我寻月下人不归
    2021-02-12 12:59

    s := s + 'some string' could be terribly slow if you do it in a loop because of the memory allocation involved. I have dome some tests that show that preallocating memory could be 132 times (YES YOU READ IT RIGHT) faster!!!!

    The code is like this:

     marker:= 1;
     CurBuffLen:= 0;
     for i:= 1 to Length(FileBody) DO
      begin
       if i > CurBuffLen then
        begin
         SetLength(s, CurBuffLen+ BuffSize);
         CurBuffLen:= Length(s)
        end;
       s[marker]:= FileBody[i];
       Inc(marker);
      end;
    

    See my answer here for details: When and Why Should I Use TStringBuilder?

    Note: my code is optimized for

    s:= s+ c

    where c is a char, but you can easily adapt it

    for s:= s + 'some string'

    .

提交回复
热议问题