Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are anonymous methods implemented under the hood?

Does Delphi "instantiate" each anonymous method (like an object)?, if so when does Delphi create this instance, and most important, when does Delphi free it?

Because anonymous method also captures external variables and extends their life time, it's important to know when these variables will be "released" from the memory.

What are the possible drawbacks to declare an anonymous method inside another anonymous method. Are circular reference possible?

like image 779
zeus Avatar asked Oct 10 '16 09:10

zeus


People also ask

What is the advantage of using anonymous methods?

The advantage of an anonymous function is that it does not have to be stored in a separate file. This can greatly simplify programs, as often calculations are very simple and the use of anonymous functions reduces the number of code files necessary for a program.

What is the use of anonymous method in C#?

Anonymous methods provide a technique to pass a code block as a delegate parameter. Anonymous methods are the methods without a name, just the body. You need not specify the return type in an anonymous method; it is inferred from the return statement inside the method body.

Which keyword is used to declare an anonymous method?

In Python, an anonymous function is a function that is defined without a name. While normal functions are defined using the def keyword in Python, anonymous functions are defined using the lambda keyword. Hence, anonymous functions are also called lambda functions.


2 Answers

Anonymous methods are implemented as interfaces with a method called Invoke that has the same signature as the anonymous method declaration. So technically a reference to function(a: Integer): string is binary compatible to this interface:

X = interface
  function Invoke(a: Integer): string;
end;

Up to a few versions ago it was even possible to call .Invoke on anonymous methods but the compiler now prevents that.

When you are declaring an anonymous method inline the compiler creates some code in the prologue of the routine to ensure that any variable that is captured does not live on the stack but on the heap (this is also the reason why you cannot inspect any captured variable during debugging because it is unfortunately lacking that information). The compiler creates a class behind that interface with fields that have the same name as the variables that you are capturing (see this blog article for more information).

As for circular references, yes. Be aware that when you for example capture an interface (or object in case of nextgen platforms where you have ARC for objects enabled) you might cause a circular reference causing a memory leak.

Also it is interesting to know that in case you have multiple anonymous methods inside the same routine they are all backed by the same compiler generated object. This might cause another situation where a memory leak might appear because one anonymous method might also capture the other and create another circular reference.

like image 114
Stefan Glienke Avatar answered Oct 18 '22 11:10

Stefan Glienke


Anonymous methods are implemented as interfaces. This article has a good explanation of how it is done by the compiler: Anonymous methods in Delphi: the internals.

In essence, the compiler generated interface has a single method named Invoke, behind which is the anonymous method that you provide.

Captured variables have the same lifetime as any anonymous methods that capture them. The anonymous method is an interface and its lifetime is managed by reference counting. Therefore, the captured variables life extends as long as does the anonymous methods that capture them.

Just as it is possible for circular references to be created with interfaces, it must equally be possible for circular references to be created with anonymous methods. Here is the simplest demonstration that I can construct:

uses
  System.SysUtils;

procedure Main;
var
  proc: TProc;
begin
  proc :=
    procedure
    begin
      if Assigned(proc) then
        Beep;
    end;
end;

begin
  ReportMemoryLeaksOnShutdown := True;
  Main;
end.

Behind the scenes the compiler creates a hidden class that implements the anonymous method interface. That class contains as data members any variables that are captured. When proc is assigned to, that increases the reference count on the implementing instance. Since proc is owned by the implementing instance, that instance therefore has taken a reference to itself.

To make this a little clearer, this program presents the identical issue but re-cast in terms of interfaces:

uses
  System.SysUtils;

type
  ISetValue = interface
    procedure SetValue(const Value: IInterface);
  end;

  TMyClass = class(TInterfacedObject, ISetValue)
    FValue: IInterface;
    procedure SetValue(const Value: IInterface);
  end;

procedure TMyClass.SetValue(const Value: IInterface);
begin
  FValue := Value;
end;

procedure Main;
var
  intf: ISetValue;
begin
  intf := TMyClass.Create;
  intf.SetValue(intf);
end;

begin
  ReportMemoryLeaksOnShutdown := True;
  Main;
end.

It is possible to break the circularity by explicitly clearing the self-reference. In the anonymous method example that looks like this:

procedure Main;
var
  proc: TProc;
begin
  proc :=
    procedure
    begin
      if Assigned(proc) then
        Beep;
    end;
  proc := nil;
end;

The equivalent for the interface variant is:

procedure Main;
var
  intf: ISetValue;
begin
  intf := TMyClass.Create;
  intf.SetValue(intf);
  intf.SetValue(nil);
end;
like image 34
David Heffernan Avatar answered Oct 18 '22 11:10

David Heffernan