I'm one of those so-called developers who got their way with Delphi without really understanding or even thinking about basics. In this case, I'm talking about strings.
While I do understand how pre-allocating memory can result in a significant speed gain. I don't understand how to use it in simple, real-world, cases (this is even more true with the TStringBuilder).
For example, let's say I have this code that recursively search a folder & add results to a hash list:
var
FilesList : TDictionary<String, Byte>; // Byte = (file = 0, folder = 1)
// ------------------------------------------------------------------------------ //
procedure AddFolder(const AFolderName : String);
var
FileName : String;
AHandle : THandle;
FindData : TWin32FindData;
begin
AHandle := FindFirstFile(PChar(AFolderName + '*'), FindData);
if (AHandle = INVALID_HANDLE_VALUE) then
Exit;
repeat
if (FindData.dwFileAttributes And FILE_ATTRIBUTE_DIRECTORY = 0) then
begin
{ Add a file. }
FileName := FindData.cFileName;
FilesList.Add(AFolderName + FileName, 0);
end
else if ((FindData.cFileName[0] <> '.') OR Not ((FindData.cFileName[1] = #0) OR (FindData.cFileName[1] = '.') And (FindData.cFileName[2] = #0))) then
begin
FileName := AFolderName + FindData.cFileName + '\';
FilesList.Add(FileName, 1);
AddFolder(FileName);
end;
until Not FindNextFile(AHandle, FindData);
Windows.FindClose(AHandle);
end;
I'm not sure if it's a good example, but in this case, it's not clear to me how pre-allocating memory to the variable FileName
would help increase the execution speed, especially that I know nothing about its length. Assuming this is possible, how?
Or is the pre-allocation technique only useful when concatenating / building strings?
Notes about my question:
The question is primarily for XE2, but feel free to reference other delphi versions as I'm sure other developers will benefit from sharing the wisdom (that is, assuming mods won't delete it as chatty or subjective)
I'm more interested in simple everyday cases where one needs to make micro-optimization in very large loops / with huge amount of data by optimizing string memory pre-allocation.
FindNextFile
. When you profiled this code, what did the break down look like? – David Heffernan