When can I Free a component create at runtime. (JavaScript Memory Management Model)

I've taken the example TMSWeb_SimpleService.web and added to it a new button. On his OnClick event, I wrote this code:

procedure TForm1.WebButton2Click(Sender: TObject);
var WebRequest :TWebHttpRequest;
begin
   WebRequest := TWebHttpRequest.Create(nil);
   try
      WebRequest.URL := 'http://192.168.10.146:8080/public';

      WebRequest.Execute(
         procedure(AResponse: string; AReq: TJSXMLHttpRequest)
         var
           JsonObject :TJSONObject;
           TheMessage :string;
         begin
           WebListBox1.Clear;
           try
              JsonObject := TJSONObject.ParseJSONValue(AResponse) as TJSONObject;
              if Assigned(jsonObject) then begin
                 TheMessage := jsonObject.GetValue('message').Value;
                 WebListBox1.Items.Add(TheMessage);
              end
              else begin
                 ShowMessage('Error: JSON not valid');
              end;
           finally
           end;
         end
      );
   finally
      WebRequest.Free;
   end;
end;

It's clear that after the Execute, the program will continue with its execution without waiting for the Response, and the next instruction is WebRequest.Free;

When the response comes from the server, the component does not exist yet.

I've thought that I could put the call to Free inside the execution, but if the program has any problem, the component is going to stay in memory forever.

Or, the model of the memory management of JavaScript has a Garbage collection, and the destruction of this kind of component is not necessary?

There is no concept of object memory management in WEB. The Free method is just a stub that does nothing. You can place .Free inside your callback for code cleaness, but it should not affect memory allocation in JavaScript

1 Like

My experience is very different.

First, I needed to remove the WebRequest.Free instruction of my code to see it working. This means that Free is not a stub. It is an actual command in JavaScript.

Second, After asking the web and Chat GPT, I discovered this:

JavaScript has an automatic memory management model known as garbage collection.

It's probably the WebRequest.Free of Pascal is translated to WebRequest := nil equivalence, which tells the Garbage Collector that this object is ready to be destroyed, but we accelerate the moment, which is fatal.

Thanks for your time in any case.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.