ar099968
ar099968

Reputation: 7537

Delphi need to free/shrink string?

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

  1. string var in a class is already free by class destroy or I need to shrink??

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;
  1. in a service (live 24/24 hours) when the run-time library frees the memory?

Upvotes: 2

Views: 2299

Answers (2)

Rob Kennedy
Rob Kennedy

Reputation: 163277

No, there is no need to free or shrink your string. Two reasons:

  1. 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.

  2. 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

Wosi
Wosi

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

Related Questions