Last active
November 17, 2021 10:40
-
-
Save omonien/bef4c365e3e221efb397bee4019a7226 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:
It indicates that the memory allocated, with a filled list, is at about 200MB. This number matches what TaskManager displays:
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.