Skip to content

Instantly share code, notes, and snippets.

@omonien
Last active November 17, 2021 10:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save omonien/bef4c365e3e221efb397bee4019a7226 to your computer and use it in GitHub Desktop.
Save omonien/bef4c365e3e221efb397bee4019a7226 to your computer and use it in GitHub Desktop.
program MemTest;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.Classes, System.SysUtils, System.Contnrs;
const
GMaxChars = 100;
GMaxItems = 1000000; //10M
// https://stackoverflow.com/a/558290/99158
function GetMemoryAllocated: UInt64;
var
st: TMemoryManagerState;
sb: TSmallBlockTypeState;
begin
GetMemoryManagerState(st);
result := st.TotalAllocatedMediumBlockSize + st.TotalAllocatedLargeBlockSize;
for sb in st.SmallBlockTypeStates do
begin
result := result + sb.UseableBlockSize * sb.AllocatedBlockCount;
end;
end;
function RandomString: string;
begin
for var i := 1 to Random(GMaxChars) + 1 do
begin
result := result + Chr(Random(20) + 32);
end;
end;
type
TFoo = class(TObject)
private
FName: string;
public
constructor Create;
property Name: string read FName write FName;
end;
{ TFoo }
constructor TFoo.Create;
begin
FName := RandomString;
end;
begin
ReportMemoryLeaksOnShutdown := true;
Writeln('Starting Memory Allocation Test ...');
Writeln('Initial memory allocated: ' + GetMemoryAllocated.ToString);
Randomize;
try
var
LFooObjects := TObjectList.Create(true);
try
for var i := 1 to GMaxItems do
begin
LFooObjects.Add(TFoo.Create);
end;
finally
Writeln('Filled list memory allocated: ' + GetMemoryAllocated.ToString);
FreeAndNil(LFooObjects);
end;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
Writeln('Final memory allocated: ' + GetMemoryAllocated.ToString);
Writeln('Done! Press ENTER');
Readln;
end.
@omonien
Copy link
Author

omonien commented Nov 17, 2021

This simple test fills an ObjectList with 10M instances of TFoo, which has a random Name:string property that will be up to 100 chars long. The length of the name is variable, so that it matches a somewhat more realistic scenario, such as with JSON files with many strings of different size.

This is a sample output:

Starting Memory Allocation Test ...
Initial memory allocated: 12856
Filled list memory allocated: 197781352
Press ENTER to continue ...

Final memory allocated: 13280
Done! Press ENTER

It indicates that the memory allocated, with a filled list, is at about 200MB. This number matches what TaskManager displays:
Bildschirmfoto 2021-11-17 um 11 29 35
After pressing ENTER, the List's allocated memory is freed and the final memory is back down to about 13KB. TaskManager still reports between 3 and 5 MB, but that's basically what it reports with an empty app too.
Bildschirmfoto 2021-11-17 um 11 33 05

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment