delphi – 为什么我释放内存后程序的内存使用率没有恢复正常?

前端之家收集整理的这篇文章主要介绍了delphi – 为什么我释放内存后程序的内存使用率没有恢复正常?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
考虑下一个示例应用程序
program TestMemory;


{$APPTYPE CONSOLE}

uses
  PsAPI,Windows,SysUtils;

function GetUsedMemoryFastMem: cardinal;
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 GetUsedMemoryWindows: longint;
var
  ProcessMemoryCounters: TProcessMemoryCounters;
begin
  Result:=0;
  ProcessMemoryCounters.cb := SizeOf(TProcessMemoryCounters);
  if GetProcessMemoryInfo(GetCurrentProcess(),@ProcessMemoryCounters,ProcessMemoryCounters.cb) then
   Result:= ProcessMemoryCounters.WorkingSetSize
  else
   RaiseLastOSError;
end;

procedure Test;
const
  Size = 1024*1024;
var
  P : Pointer;
begin
  GetMem(P,Size);

      Writeln('Inside');
      Writeln('FastMem '+FormatFloat('#,',GetUsedMemoryFastMem));
      Writeln('Windows '+FormatFloat('#,GetUsedMemoryWindows));
      Writeln('');

  FreeMem(P);
end;

begin
      Writeln('Before');
      Writeln('FastMem '+FormatFloat('#,GetUsedMemoryWindows));
      Writeln('');

      Test;

      Writeln('After');
      Writeln('FastMem '+FormatFloat('#,GetUsedMemoryWindows));
      Writeln('');
      Readln;
end.

应用程序返回的结果是

Before
FastMem 1.844
Windows 3.633.152

Inside
FastMem 1.050.612
Windows 3.637.248

After
FastMem 2.036
Windows 3.633.152

我想知道为什么内存使用的结果在之前和之后是不同的:

解决方法

任何内存管理器(包括FastMM)都会产生一些开销,否则Delphi可能只是使用了Windows内存管理.

您观察到的差异是开销:

> FastMM用于跟踪内存使用情况的结构,> FastMM尚未返回到Windows内存管理的内存块,以便在将来优化类似的内存分配.

猜你在找的Delphi相关文章