delphi 内存泄漏检测

FormCreate 加一条 或者在project里加上,就是fastmm
ReportMemoryLeaksOnShutdown:=true;

  Application.Initialize;
  Application.MainFormOnTaskbar := True;

ReportMemoryLeaksOnShutdown:=true;

退出程序的时候,如果有内存泄漏,会弹出一个对话框.

*1就是有1个,3就是有3个,2就是有2个

13 - 20 bytes: TJSONNumber x 1, TJSONObject x 1, TJSONString x 3, TJSONPair x 2, UnicodeString x 2
21 - 28 bytes: UnicodeString x 1, Unknown x 1
29 - 36 bytes: UnicodeString x 1
37 - 44 bytes: TList<System.JSON.TJSONPair> x 1

 一、JO 要释放

jo := TJSONObject.ParseJSONValue('{"name": "John Smith", "age": 33}') as TJSONObject;

这个用完jo.free,否则就有内存泄漏 或者 freeandnil(jo);

如果jo多次使用,下面2种方法都可以,释放没问题。

//if jo<>nil then  freeandnil(jo);
if jo<>nil then  jo.Free;

二、Serialize 有泄漏

self.injson := system.JSON.Serializers.TJsonSerializer.Create.Serialize<TPerson>(inp);

改为

var tt :=  system.JSON.Serializers.TJsonSerializer.Create;
self.injson:= Serializer.Serialize<TPerson>(inp);
tt.Free;

TJsonSerializer.Create.Deserialize也有泄漏换成 create free就好了

三、TJSONArray  无泄漏

var jr:tjsonarray;

jr := jo.GetValue<TJSONArray>('data.dataList') ;

      for i := 0 to jr.Count - 1 do
  begin
    jrow := jr.Get(i) as TJSONObject;
  self.Caption:=  jrow.GetValue<string>('ampm');

end;

封装后调用简单,无内存泄漏

  TKPJSON=class
    class function  Deserialize<T>(const AJson: string): T;
    class function  Serialize<T>(const AValue: T): string;
  end;

  class function TKPJSON.Deserialize<T>(const AJson: string): T;
begin
  var tt :=  system.JSON.Serializers.TJsonSerializer.Create;
  result:= tt.Deserialize<T>(ajson);
  tt.Free;
end;

class function TKPJSON.Serialize<T>(const AValue: T): string;
begin
var tt :=  system.JSON.Serializers.TJsonSerializer.Create;
result:= tt.Serialize<T>(AValue);
tt.Free;
end;

self.injson:=  TKPJSON.Serialize<T100110>(inp);//简单到一行代码
var top :=  TKPJSON.Deserialize<T100110>(self.injson);//简单到一行代码

原文地址:https://www.cnblogs.com/cb168/p/13189264.html