> On Jun 6, 2022, at 8:26 AM, Hairy Pixels <[email protected]> wrote:
>
> I think what the compiler needs to do is internally support a variant record
> type and switch to the correct function type at runtime. Something like this:
>
> TCallback = record
> kind: byte;
> case byte of
> 0: (proc: procedure);
> 1: (ref: reference to procedure);
> 2: (nested: procedure is nested);
> 3: (obj: procedure of object);
> end;
I found Anthony's email in the archive where he explain this optimization very
nicely but he missed another aspect of it. Take for example this code:
type
TCallback = reference to procedure;
procedure CallMe(callback: TCallback);
begin
callback();
end;
var
i: integer = 1;
begin
CallMe(procedure
begin
writeln(‘hello ‘, i);
end);
end;
Here state needs to be captured but the structure capturing it doesn’t need to
be a heap allocated interface backed class because it never leaves the calling
scope. FPC already has an existing closure type for nested functions which is
far more efficient and could be implemented if there was this variant structure
behind the scenes which could accept it.
So the optimization has two components:
1) If there is no anonymous function then obviously no state needs to be
captured and the function reference should be either a function pointer or a
“of object” pointer.
2) If the there is captured state but that closures never leaves the calling
scope then it can be optimized as a “is nested” function pointer.
Unlike most of my feature requests this one actually affects performance and
should seriously be considered. It’s nothing crazy like constant propagation
for inlining function pointers but it does require a new dynamic type be
introduced to the compiler which can wrap up these variant function pointers
and dispatch the correct one at runtime. Needless to say if it’s within my
ability I will elect myself to implement this if it’s permitted by the compiler
team.
Regards,
Ryan Joseph
_______________________________________________
fpc-pascal maillist - [email protected]
https://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-pascal