[fpc-pascal] Speed question for strings

L L at z505.com
Sat Nov 19 07:46:55 CET 2005


Why is the first and third example *so* much faster than the second example?
Significantly faster.

There's really not that much difference between the string concatenation.


//Example 1: (seems fast)
function StrLoadFile_test1(FileName: string): string;
var
  F: text;
  c: char;
  str1,Line: string;
begin
  result:= ''; //safety
  str1:= '';
  if FileExists(FileName) = false then
  begin
   result:= ''; //returns nothing if file not found
   exit;
  end;
  Assign(F, FileName);
  Reset(F);
  while not Eof(F) do
  begin
    Read(F, C);
    result:= result + C;
  end;
  close(F); //close up file
end;

//Example 2: (definitely slow)
function StrLoadFile_test2(FileName: string): string;
var
  F: text;
  str1,Line: string;
begin
  result:= ''; //safety
  str1:= '';
  if FileExists(FileName) = false then
  begin
   result:= ''; //returns nothing if file not found
   exit;
  end;
  Assign(F, FileName);
  Reset(F);
  while not Eof(F) do
  begin
    ReadLn(F, Line);
    result:= result + Line + #13#10;
  end;
  close(F); //close up file
end;

//Example 3: (seems fast)
function StrLoadFile_test3(FileName: string): string;
var
  F: text;
  str1,Line: string;
begin
  result:= ''; //safety
  str1:= '';
  if FileExists(FileName) = false then
  begin
   result:= ''; //returns nothing if file not found
   exit;
  end;
  Assign(F, FileName);
  Reset(F);
  while not Eof(F) do
  begin
    ReadLn(F, Line);
    result:= result + Line; //note: took out carriage return.
  end;
  close(F); //close up file
end;


What's the deal with one extra CRLF? The line is being concatenated each time, so I
don't see why it is *so* much slower with concatenating an extra CRLF each time. I
could see if it made a minimal impact.. but it is not minimal, it is hugely majorly
significant.

There even better ways to do this StrLoadFile of course (reading in large chunks). I
'm just wondering about this particular situation though, for the knowledge. I just
don't see how it can be significantly slower, since in all cases we are still
concatenating in the loop .. the slow one just contains one small extra
concatenation.

In order to see the speed difference, try a 1MB or 5MB file.

--
L505





More information about the fpc-pascal mailing list