Free and Garbage Collection
By Erick Engelke
November 14, 2024
Most of us come from a Delphi world, so when we are done with objects, we are sure to free or dispose of them.
JavaScript is a language with automatic Garbage Collection (GC), meaning memory is automatically freed at some time after it is no long in scope. You cannot control when the GC happens, but it does it often enough that usually you don’t run out of available RAM unless you have a memory leak.
Let’s investigate what that means. I’ve written the following code as you would in Delphi.
procedure TForm1.Button1Click(Sender: TObject);
begin
label := TLabel.Create( self );
label.caption := 'hi';
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
label.free;
label := Nil;
end;
Of course my Button2Click handler assigns Nil after the Free to ensure I don’t reuse the freed memory.
First we’ll look at the generated JavaScript for the Create button:
test0001_tform1.$p.button1click = function(sender)
{
var $t = this;
$t.tform1_label = weblabels_tlabel.$p.create_1.call(new weblabels_tlabel(), $t);
$t.tform1_label.tlabelcontrol_setcaption("hi");
};
Pretty straight forward.
Now let’s look at the second Button handler:
test0001_tform1.$p.button2click = function(sender)
{
var $t = this;
$t.tform1_label = tobject.$p.free($t.tform1_label);
$t.tform1_label = null;
};
So label.Free() translates to label := …free()… interesting
If you single step through it, you will see tform_label is set back to NULL before my second line.
The lable := Nil is redundant, EWB has already assigned it a Nil/NULL value. It doesn’t hurt, and it makes you feel better as a programmer, but it’s not necessary.
That’s why…
if Assigned( label ) ...
will return True after a variable is freed.