Reputation: 7537
In this example, in a server service (live 24/24 hours), do I need to free/shrink aBaz
for free clean/memory?
function foo(const aBar : string) : boolean;
var
aBaz : string;
begin
aBaz := 'very very long string';
Result := (aBar = aBaz);
aBaz := ''; // shrink `aBaz` for free memory
end;
Update
Eg.:
class Foo = class
FBar : string;
public
constructor Create; overload;
destructor Destroy; reintroduce;
end;
constructor Foo.Create(const ABar : string);
begin
FBar := ABar;
end;
destructor Foo.Destroy;
begin
FBar := ''; // destructor already free memory or I need to shrink?
end;
Upvotes: 2
Views: 2299
Reputation: 163277
No, there is no need to free or shrink your string. Two reasons:
This particular string is a string literal. It's not allocated on the heap. The compiler includes a literal copy of that string in your EXE, and when you assign it to aBaz
, the variable refers directly to that read-only memory in your EXE file. Nothing gets allocated, so there's nothing to free.
Strings in general are subject to automatic reference counting. When a string variable goes out of scope (which is what happens to aBaz
when you reach the end
keyword in this function), the string that the variable refers to has its reference count decremented. If the resulting count is zero, then the run-time library frees the memory associated with the string.
The compiler inserts reference-managing code automatically. You don't need to do anything with it.
Upvotes: 12
Reputation: 45233
No, you don't need to free strings on your own. Strings are managed automatically.
aBaz
will be automatically freed when foo
has finished. The string value will be removed from memory in case there is no other string variable containing the same value.
Upvotes: 5